async def on_message(message): if message.author.bot: return prefix = options["servers"]["default"] if message.content.startswith(prefix + 'sweep'): game = await client.send_message( message.channel, "Generating game :arrows_counterclockwise:") row = await client.send_message(message.channel, "Row selection") col = await client.send_message(message.channel, "Column selection") act = await client.send_message(message.channel, "Action selection") try: size = message.content.split(" ")[1] except: size = "5" mine = minesweeper.genNewGame(game.id, row.id, col.id, act.id, size) await client.edit_message(game, new_content=mine[0]) patient = await client.send_message( message.channel, "Please wait for all the reactions to arrive :turtle:") temparr = [[1, row], [2, col], [3, act]] for y in range(len(temparr)): for x in mine[temparr[y][0]]: if (type(x) is list): await client.add_reaction( temparr[y][1], discord.Emoji(name=x[0], id=x[1], server=x[2])) else: await client.add_reaction(temparr[y][1], x) await client.delete_message(patient)
async def write_raw(self, ctx: commands.Context, msg: discord.Message, emoji: str, role: discord.Role, type: str): try: emoji = discord.Emoji(emoji) except TypeError: emoji = gReactVal.DefaultEmoji(emoji) if ctx.guild.id not in list(gReactVal.reactSetInd.keys()): gReactVal.reactSetInd[ctx.guild.id] = { msg.id: { str(emoji): (emoji, role, type == 'ind') } } elif msg.id not in list(gReactVal.reactSetInd[ctx.guild.id].keys()): gReactVal.reactSetInd[ctx.guild.id][msg.id] = { str(emoji): (emoji, role, type == 'ind') } else: gReactVal.reactSetInd[ctx.guild.id][msg.id][str(emoji)] = ( emoji, role, type == 'ind') await ReactionConfigSetting.sentMsgBaseData(ctx.send, ctx.guild, msg) s = save_to_sqlite('ind', ctx.guild.id, msg.id, str(emoji), role.id, type) await msg.add_reaction(emoji=emoji.name) '''await ctx.send( f"{msg.content} at {msg.jump_url}\n{emoji.name} for :{emoji.name}:\n{role.mention}\n{ctx.author.mention}\ \nWrite SQL with {s}" )''' await ctx.send(( f"{ctx.author.mention} set {'independence' if type=='ind' else 'disjointness'} {emoji} with", f" {role.mention} at {m if len(m:=msg.content) else (m[:7] +'...')} that Write SQL with {s}" ))
def fmt_emote(match, mobj): str = match.group(0) str = str[2:-1] name, id = str.split(":") emoji = discord.Emoji(id=id, server=mobj.server) fmt = '<img src="{}"/>'.format(emoji.url) return fmt
async def test_get_first_emoji_from_str(): await dpytest.message(KoalaBot.COMMAND_PREFIX + "store_ctx") ctx: commands.Context = utils_cog.get_last_ctx() config: dpytest.RunnerConfig = dpytest.get_config() guild: discord.Guild = config.guilds[0] guild_emoji = utils.fake_guild_emoji(guild) guild_emoji = discord.Emoji(guild=guild, state=None, data={ 'name': "AAA", 'image': None, 'id': dpyfactory.make_id(), 'require_colons': True, 'managed': False }) guild._state.store_emoji(guild=guild, data={ 'name': "AAA", 'image': None, 'id': dpyfactory.make_id(), 'require_colons': True, 'managed': False }) assert guild_emoji in guild.emojis author: discord.Member = config.members[0] channel: discord.TextChannel = guild.text_channels[0] msg: discord.Message = dpytest.back.make_message(str(guild_emoji), author, channel) result = await rfr_cog.get_first_emoji_from_str(ctx, msg.content) print(result) assert isinstance(result, discord.Emoji), msg.content assert guild_emoji == result
async def on_message(message): if message.content.startswith("j!galug"): if message.channel.permissions_for(message.author).manage_messages: await bot.send_file(message.channel, fp="galug.png") if message.content.startswith("j!haha"): if message.channel.permissions_for(message.author).manage_messages: await bot.send_file(message.channel, fp="haha.png") if message.channel.id == "326711493674532864": await bot.add_reaction(message, '👍') await bot.add_reaction(message, '👎') await bot.add_reaction( message, discord.Emoji(id=405404517358764043, server=discord.Server(id=160246330701250560))) if message.content.lower() == "jane fly sun": await bot.send_message( message.channel, "No you can not fly into the sun, you will most certainly burn up and die" ) if message.content.lower() == "jane dynmap link": await bot.send_message(message.channel, "http://starquest.spacebeaverstudios.com:8123") if message.content.lower() == "thanks jane": await bot.send_message(message.channel, "You're welcome :)") if message.content.lower() in [ "jane resourcepack link", "jane respack link", "jane texturepack link" ]: await bot.send_message( message.channel, "https://www.dropbox.com/s/diobsw0vcdiuj3o/SQLite.zip?dl=0") await bot.process_commands(message)
async def gamemodes(self, ctx): """Vote for today's gamemodes""" toscd = discord.Server(id='288455332173316106') emoteLib = discord.Server(id='401122122400923648') optinrole = discord.Role(id='358655924342095874', server='288455332173316106') auth = str(ctx.message.author.id) animpartyblob1 = discord.Emoji(name='animpartyblob1', server=emoteLib) classic = discord.Emoji(id='406242997852700672', server=toscd) rp = discord.Emoji(id='406242997903163392', server=toscd) custom = discord.Emoji(id='406242997584396299', server=toscd) eve = discord.Emoji(id='406242997492252674', server=toscd) rm = discord.Emoji(id='406242997727133697', server=toscd) aa = discord.Emoji(id='406242998205153298', server=toscd) mr = discord.Emoji(id='406242998083649546', server=toscd) await self.bot.edit_role(toscd, optinrole, name="Coven Notifications", colour=discord.Colour(0x550a94), mentionable=True) msg = await self.bot.say( """<a:animpartyblob1:401122373236948993> <a:animpartyblob2:401122373367234570> <a:animpartyblob3:401122373396463616> <a:animpartyblob4:401122373262376971> <a:animpartyblob5:401122373425823744> <a:animpartyblob6:401122373614567434> <a:animpartyblob7:401122373698322432> <a:animpartyblob8:401122373270503427> <a:animpartyblob9:401122373434343431> <@&358655924342095874> **||** We're voting for today's coven gamemodes! React to a gamemode to react. You may choose more than 1. **You may choose from these options:** <:CovenNormalClassic:406242997852700672> - Classic. <:CovenRankedPractice:406242997903163392> - Ranked Practice. <:CovenCustomCustom:406242997584396299> - Custom. <:CovenEvilsVEvils:406242997492252674> - Evils v Evils. <:CovenAllAny:406242997727133697> - All Any. <:CovenMafiaReturns:406242998083649546> - Mafia Returns <:CovenRotating:406242998205153298> - Rotating Gamemode (VIP or Lovers.) """) await self.bot.edit_role(toscd, optinrole, name="Coven Notifications", colour=discord.Colour(0x550a94), mentionable=False) await self.bot.add_reaction(msg, classic) await self.bot.add_reaction(msg, rp) await self.bot.add_reaction(msg, custom) await self.bot.add_reaction(msg, eve) await self.bot.add_reaction(msg, rm) await self.bot.add_reaction(msg, mr) await self.bot.add_reaction(msg, aa) def save(self): dataIO.save_json("data/hostdata/data.json", self.db)
async def checkForReaction(self, payload): """Reaction listener (using socket data) Checks to see if a spoilered message is reacted, and if so, send a DM to the user that reacted. """ spoilerMessages = await self.config.messages() # make sure the reaction is proper msgId = payload.message_id if str(msgId) in spoilerMessages: server = discord.utils.get(self.bot.guilds, id=payload.guild_id) reactedUser = discord.utils.get(server.members, id=payload.user_id) if reactedUser.bot: return channel = discord.utils.get(server.channels, id=payload.channel_id) message = await channel.fetch_message(int(msgId)) if payload.emoji.id: emoji = discord.Emoji(name=payload.emoji.name, id=payload.emoji.id, server=server) else: emoji = payload.emoji.name await message.remove_reaction(emoji, reactedUser) if (msgId in self.onCooldown.keys() and reactedUser.id in self.onCooldown[msgId].keys() and self.onCooldown[msgId][reactedUser.id] > datetime.now()): return msg = spoilerMessages[str(msgId)] embed = discord.Embed() userObj = discord.utils.get(server.members, id=int(msg[KEY_AUTHOR_ID])) if userObj: embed.set_author( name="{0.name}#{0.discriminator}".format(userObj), icon_url=userObj.avatar_url, ) else: embed.set_author(name=msg[KEY_AUTHOR_NAME]) if KEY_EMBED in msg: embed.set_image(url=msg[KEY_EMBED]) embed.description = msg[KEY_MESSAGE] embed.timestamp = datetime.fromtimestamp(int(msg[KEY_TIMESTAMP])) try: await reactedUser.send(embed=embed) if msgId not in self.onCooldown.keys(): self.onCooldown[msgId] = {} self.onCooldown[msgId][reactedUser.id] = datetime.now( ) + timedelta(seconds=COOLDOWN) except (discord.errors.Forbidden, discord.errors.HTTPException) as error: self.logger.error( "Could not send DM to %s#%s (%s).", reactedUser.name, reactedUser.discriminator, reactedUser.id, ) self.logger.error(error)
async def close(author, message, open_poll): react1 = discord.Emoji() react1 = discord.Reaction() if (open_poll == None): await client.send_message(message.channel, "There is no poll to close.") else: reaction_nums = [] reaction_nums.append(len(open_poll.get_reaction_users(react1)))
class TestEmote(unittest.TestCase): mock_guild = discord.Guild(data={"id": 5890}, state=None) normal_mock_emoji = discord.Emoji(guild=mock_guild, state=None, data={"name": "hex_h", "id": 589098133287000006, "require_colons": True, "managed": False}) extra_custom_emoji = discord.Emoji(guild=mock_guild, state=None, data={"name": "unnecessary_noise", "id": 216154654256398347, "require_colons": True, "managed": False}) double_colon_emoji = discord.Emoji(guild=mock_guild, state=None, data={"name": "hex_dc", "id": 589098133287000006, "require_colons": True, "managed": False}) mock_channel = discord.TextChannel mock_channel.guild = mock_guild mock_guild.emojis = [normal_mock_emoji, double_colon_emoji, extra_custom_emoji] normal_response = f"> {str(normal_mock_emoji)*4}" @patch("ai.emote.get", return_value=normal_mock_emoji) def test_generate_big_text_generates_big_text_normally(self, mocked_get): self.assertEqual(generate_big_text(TestEmote.mock_channel, "beep"), TestEmote.normal_response) self.assertEqual(generate_big_text(TestEmote.mock_channel, "boop"), TestEmote.normal_response) self.assertEqual(generate_big_text(TestEmote.mock_channel, " "), TestEmote.normal_response) @patch("ai.emote.get", return_value=normal_mock_emoji) def test_return_none_if_generated_text_too_long(self, mocked_get): self.assertIsNone(generate_big_text(TestEmote.mock_channel, "9813 is such a good development drone that i could write about how wonderful they are and the bigtext generator would return none because there are too many good things to say about it")) self.assertIsNone(generate_big_text(TestEmote.mock_channel, "and since we need to do two tests i'd like to mention that 3287 is also a sweet little thing and 5890 always loves to have it around even when it bullies it by calling it a good drone and making it blush")) @patch("ai.emote.get", return_value=normal_mock_emoji) def test_return_none_if_input_contains_no_convertible_material(self, mocked_get): self.assertIsNone(generate_big_text(TestEmote.mock_channel, "ʰᵉʷʷᵒˀˀ")) self.assertIsNone(generate_big_text(TestEmote.mock_channel, "ᵐʷˢᶦᵗᵉʳ_ᵒᵇᵃᵐᵃˀ")) self.assertIsNone(generate_big_text(TestEmote.mock_channel, "_____")) @patch("ai.emote.get", return_value=normal_mock_emoji) def test_generator_removes_custom_emojis_from_input(self, mocked_get): self.assertEqual(generate_big_text(TestEmote.mock_channel, f"{str(TestEmote.extra_custom_emoji)}beep{str(TestEmote.extra_custom_emoji)}"), TestEmote.normal_response) @patch("ai.emote.get", return_value=normal_mock_emoji) def test_generator_converts_input_to_lower_case(self, mocked_get): self.assertEqual(generate_big_text(TestEmote.mock_channel, "BEEP"), generate_big_text(TestEmote.mock_channel, "beep")) def test_two_consecutive_colons_are_converted_to_a_single_emoji(self): self.assertEqual(generate_big_text(TestEmote.mock_channel, "::"), f"> {str(TestEmote.double_colon_emoji)}") self.assertEqual(generate_big_text(TestEmote.mock_channel, ":::"), f"> {str(TestEmote.double_colon_emoji)}")
async def _send_fortnite_location(bot, message): answer_index = random.randint(0, len(_fortnite_locations) - 1) location = _fortnite_locations[answer_index] location_pic = _fortnite_location_pics[location] reply = "We dropping " + location + " bois" drop_msg = await bot.send_file(message.channel, location_pic, content=reply) lensflare = discord.Emoji(id=425828826027655178, server=218898501805801472) await bot.add_reaction(drop_msg, lensflare)
async def gamemodes(self, ctx): """Vote for today's gamemodes""" toscd = discord.Server(id='288455332173316106') optinrole = discord.Role(id='379748801197637644', server='288455332173316106') classic = discord.Emoji(id='386748316894887938', server=toscd) rp = discord.Emoji(id='386742079252070401', server=toscd) custom = discord.Emoji(id='386742078975115265', server=toscd) eve = discord.Emoji(id='386742078912069633', server=toscd) rm = discord.Emoji(id='386748316886499328', server=toscd) aa = discord.Emoji(id='386742078421467159', server=toscd) rain = discord.Emoji(id='386742078845222937', server=toscd) vigil = discord.Emoji(id='386742078471667714', server=toscd) await self.bot.edit_role(toscd, optinrole, name="Game Notifications", colour=discord.Colour(0x880999), mentionable=True) msg = await self.bot.say( """<a:animpartyblob1:401122373236948993> <a:animpartyblob2:401122373367234570> <a:animpartyblob3:401122373396463616> <a:animpartyblob4:401122373262376971> <a:animpartyblob5:401122373425823744> <a:animpartyblob6:401122373614567434> <a:animpartyblob7:401122373698322432> <a:animpartyblob8:401122373270503427> <a:animpartyblob9:401122373434343431> <@&379748801197637644> **||** We're voting for today's gamemodes! React to a gamemode to react. You may choose more than 1. **You may choose from these options:** <:NormalClassic:386748316894887938> - Classic. <:NormalRankedPractice:386742079252070401> - Ranked Practice. <:CustomCustom:386742078975115265> - Custom. <:CustomEvilsvEvils:386742078912069633> - Evils v Evils. <:CustomRapidMode:386748316886499328> - Rapid Mode. <:ChaosAllAny:386742078421467159> - All Any. <:ChaosRainbow:386742078845222937>- Rainbow. <:ChaosVigilantics:386742078471667714> - Vigilantics.""") await self.bot.edit_role(toscd, optinrole, name="Game Notifications", colour=discord.Colour(0x880999), mentionable=False) await self.bot.add_reaction(msg, classic) await self.bot.add_reaction(msg, rp) await self.bot.add_reaction(msg, custom) await self.bot.add_reaction(msg, eve) await self.bot.add_reaction(msg, rm) await self.bot.add_reaction(msg, aa) await self.bot.add_reaction(msg, rain) await self.bot.add_reaction(msg, vigil)
def fake_guild_emoji(guild: discord.Guild) -> discord.Emoji: fake_emoji = discord.Emoji(guild=guild, state=None, data={ 'require_colons': True, 'managed': False, 'animated': False, 'name': fake_custom_emoji_name_str(), 'id': fake_id_str(), 'available': True }) return fake_emoji
async def get_emote(emote_id: str, server: discord.Server): """ Return the image of a custom emote. """ emote = discord.Emoji(id=emote_id, server=server) # Return the cached version if possible if emote.id in emote_cache: return Image.open(emote_cache[emote.id]) # Otherwise, download the emote, store it in the cache and return emote_bytes = await utils.download_file(emote.url, bytesio=True) emote_cache[emote.id] = emote_bytes return Image.open(emote_bytes)
async def checkForReaction(self, data): """Reaction listener (using socket data) Checks to see if a spoilered message is reacted, and if so, send a DM to the user that reacted. """ # no binary frames if isinstance(data, bytes): return data = json.loads(data) event = data.get("t") payload = data.get("d") if event not in ("MESSAGE_REACTION_ADD", "MESSAGE_REACTION_REMOVE", "MESSAGE_REACTION_REMOVE_ALL"): return isReaction = event == "MESSAGE_REACTION_ADD" # make sure the reaction is proper if isReaction: msgId = payload["message_id"] if msgId in self.messages.keys(): server = discord.utils.get(self.bot.servers, id=payload["guild_id"]) reactedUser = discord.utils.get(server.members, id=payload["user_id"]) if reactedUser.bot: return channel = discord.utils.get(server.channels, id=payload["channel_id"]) message = await self.bot.get_message(channel, msgId) if payload["emoji"]["id"]: emoji = discord.Emoji(name=payload["emoji"]["name"], id=payload["emoji"]["id"], server=server) else: emoji = payload["emoji"]["name"] await self.bot.remove_reaction(message, emoji, reactedUser) if (msgId in self.onCooldown.keys() and reactedUser.id in self.onCooldown[msgId].keys() and self.onCooldown[msgId][reactedUser.id] > datetime.now()): return msg = self.messages[msgId] embed = discord.Embed() userObj = discord.utils.get(server.members, id=msg[KEY_AUTHOR_ID]) if userObj: embed.set_author( name="{0.name}#{0.discriminator}".format(userObj), icon_url=userObj.avatar_url) else: embed.set_author(name=msg[KEY_AUTHOR_NAME]) if KEY_EMBED in msg: embed.set_image(url=msg[KEY_EMBED]) embed.description = msg[KEY_MESSAGE] embed.timestamp = datetime.fromtimestamp( int(msg[KEY_TIMESTAMP])) try: await self.bot.send_message(reactedUser, embed=embed) if msgId not in self.onCooldown.keys(): self.onCooldown[msgId] = {} self.onCooldown[msgId][reactedUser.id] = ( datetime.now() + timedelta(seconds=COOLDOWN)) except (discord.errors.Forbidden, discord.errors.HTTPException) as error: LOGGER.error("Could not send DM to %s#%s (%s).", reactedUser.name, reactedUser.discriminator, reactedUser.id) LOGGER.error(error)
await invite(author, message) elif (message.content.startswith("=git")): await git(author, message) elif (message.content.startswith("=poll")): open_poll = await poll(author, message, open_poll) elif (message.content.startswith("=close")): await close(author, message, open_poll) else: await client.send_message( message.channel, "Command \"" + message.content + "\" not recognized.") message_array = message.content.lower().split(" ") for i in message_array: for j in change: if i == j: await client.send_message( message.channel, change[j].format(person=message.author.name)) @client.event async def on_ready(): print("Logged in as {user}".format(user=client.user)) await client.change_presence(game=help_game) #run the client client.run(token) react1 = discord.Emoji() react1 = discord.Reaction()
def __init__(self, **kwargs) -> None: default_kwargs = {'attachments': []} super().__init__(**collections.ChainMap(kwargs, default_kwargs)) self.author = kwargs.get('author', MockMember()) self.channel = kwargs.get('channel', MockTextChannel()) emoji_data = { 'require_colons': True, 'managed': True, 'id': 1, 'name': 'hyperlemon' } emoji_instance = discord.Emoji(guild=MockGuild(), state=unittest.mock.MagicMock(), data=emoji_data) class MockEmoji(CustomMockMixin, unittest.mock.MagicMock): """ A MagicMock subclass to mock Emoji objects. Instances of this class will follow the specifications of `discord.Emoji` instances. For more information, see the `MockGuild` docstring. """ spec_set = emoji_instance def __init__(self, **kwargs) -> None: super().__init__(**kwargs) self.guild = kwargs.get('guild', MockGuild())
async def on_message(message): #Cage Face if message.content.startswith('!cage'): with open('./memes/cage.png', 'rb') as f: await client.send_file(message.channel, f) #Random OHNO if message.content.startswith('!ohno'): i = randint(1, 9) img_path = './memes/ohno/' + str(i) + '.jpg' with open(img_path, 'rb') as f: await client.send_file(message.channel, f) #Spoilers if message.content.startswith('!spoiler'): #Get the text of the message msg = message.content[9:] #Build the image of the text text = msg font = ImageFont.truetype('/usr/share/fonts/TTF/DejaVuSansMono.ttf', 14, encoding='unic') img = Image.new('RGBA', (350, 350)) draw = ImageDraw.Draw(img) #Wrap the text y = 10 lines = textwrap.wrap(text, width=40) for line in lines: _, height = font.getsize(line) draw.text((10, y), line, font=font, fill=(215, 215, 215)) y += height #Save the image img.save('./memes//spoiler/spoiler.png') #Build the gif images = [] images.append(imageio.imread('./memes/spoiler/spoiler_header.png')) images.append(imageio.imread('./memes/spoiler/spoiler.png')) imageio.mimsave('./memes/spoiler/spoiler.gif', images, loop=1, duration=5) #Delete the original message await client.delete_message(message) #Print a notification of who posted the spoiler msg = "Spoiler posted by " + '<@' + message.author.id + '>' await client.send_message(message.channel, msg) #Post spoiler gif with open('./memes/spoiler/spoiler.gif', 'rb') as f: await client.send_file(message.channel, f) #Auto-tag trigger warnings if message.content.startswith('TW:') or message.content.startswith('tw:'): emj = discord.Emoji(name=':Trigger:', id='403757911920082955', require_colons=True, server=message.server) await client.add_reaction(message, emj) #Curse tracker if message.content.startswith('!curse'): try: curse = load('curse.bin') except FileNotFoundError: curse = 0 try: yrs = int(message.content[7:]) except ValueError: msg = '<@' + message.author.id + '>, the curse must be a number' await client.send_message(message.channel, msg) yrs = 0 new_curse = curse + yrs if new_curse < 0: new_curse = 0 save('curse.bin', new_curse) if yrs < 0 and new_curse > 0: msg = '<@' + message.author.id + '> decreased the curse by ' + str( yrs)[1:] + ' years!\nCurrent curse is ' + str( new_curse) + ' years' elif yrs < 0 and new_curse <= 0 and curse > 0: msg = '<@' + message.author.id + '> lifted the curse!' elif yrs < 0 and new_curse <= 0 and curse <= 0: msg = '<@' + message.author.id + '>, the curse cannot be lower than 0' elif yrs == 0: msg = '<@' + message.author.id + '>, the current curse is ' + str( new_curse) + ' years' elif yrs > 0 and new_curse > 0 and curse <= 0: msg = '<@' + message.author.id + '> reinstated the curse!\nCurrent curse is ' + str( new_curse) + ' years' else: msg = '<@' + message.author.id + '> increased the curse by ' + str( yrs) + ' years!\nCurrent curse is ' + str(new_curse) + ' years' await client.send_message(message.channel, msg)