async def parse_line(line): ''' Parses a macro line ''' if line.split()[0].lower() == "wait": if print_queue: # We have run into a wait, send ze messages await message.channel.send("\n".join(print_queue)) print_queue.clear() await asyncio.sleep(float(line.split()[1])) else: # Trick discord.py into parsing this command as a bot view = StringView(line) ctx = commands.Context(prefix=bot_prefix, view=view, bot=bot, message=message) invoker = view.get_word() ctx.invoked_with = invoker if (command := bot.all_commands.get(invoker) ) and not command.qualified_name == "macro": if print_queue: # We have run into a command, send ze messages await ctx.send("\n".join(print_queue)) print_queue.clear() # invoke a command ctx.command = command await bot.invoke(ctx) else:
def fake_ctx(bot, command, guild): # Used to call commands # from within the bot itself if isinstance(command, str): command = bot.get_command(command) if not isinstance(command, commands.Command): raise ValueError( f'command must be either a str or Command type, not {type(command)}' ) stringview = commands.view.StringView( f'{bot.parsed_command_prefix}{command.name}') message_dict = { 'id': 0, 'attachments': [], 'embeds': [], 'edited_timestamp': None, 'type': None, 'pinned': False, 'mention_everyone': False, 'tts': False } message_dict['content'] = f'{bot.parsed_command_prefix}{command.name}' message = discord.message.Message(state='lol', channel=guild.text_channels[0], data=message_dict) return commands.Context(message=message, bot=bot, prefix=bot.parsed_command_prefix, invoked_with=command.name, view=stringview, command=command)
async def on_reaction_add(self, reaction, user): """ check if users clicked the play button on executable code the bot has to be a reactor on the executable message """ message = reaction.message if not self.is_graphviz_message(message.content): return if message.author.bot or user.bot or message.author != user: return if str(reaction.emoji) != "▶": return if self.bot.user not in await reaction.users().flatten(): return self.log.info(f"{user} has reacted on graphviz message") ctx = commands.Context( prefix=self.bot.command_prefix, guild=message.guild, channel=message.channel, message=message, author=user, ) await self.digraph.callback(self, ctx, equation=message.content.strip("```")) await ctx.message.remove_reaction("▶", ctx.author) await ctx.message.remove_reaction("▶", self.bot.user)
async def wrapper(*args, **kwargs): bot = args[0].bot payload = args[1] if not payload.guild_id: return if valid_emojis and payload.emoji.name not in valid_emojis: return channel = bot.get_channel(int(payload.channel_id)) guild = channel.guild user = guild.get_member(int(payload.user_id)) if not user or user.bot: return message = await channel.fetch_message(int(payload.message_id)) ctx = commands.Context( bot=bot, channel=channel, guild=guild, message=message, prefix=bot.command_prefix, command=ReactionCommand(), ) # Author needs to be changed after creation as it reassigns it during creation ctx.author = user ctx.command.cog_name = args[0].qualified_name ctx.command.name = func.__name__ await func(args[0], ctx, payload.emoji) spreadsheet.Spreadsheet.pickle_from_id.cache_clear()
async def mystbin(self, ctx, syntax: str, *, data: str): paste = await self.bot.mystbin.post(data, syntax=syntax) context = commands.Context( prefix=ctx.prefix, message=await self.bot.get_guild(801287324109373481).get_channel( 801920760565727263).fetch_message(801920951600152587)) await context.send(str(paste)) return await ctx.send(str(paste))
async def on_thread_ready(self, thread, creator, category, initial_message): """Sends out menu to user""" menu_config = await self.db.find_one({'_id': 'config'}) if menu_config: message = DummyMessage(copy.copy(initial_message)) message.author = self.bot.modmail_guild.me message.content = menu_config['content'] #genesis = thread.recipient_genesis_message #await genesis.delete() msg, _ = await thread.reply(message, anonymous=True) for r in menu_config['options']: await msg.add_reaction(r) await asyncio.sleep(0.3) try: reaction, _ = await self.bot.wait_for( 'reaction_add', check=lambda r, u: r.message == msg and u == thread. recipient and str(r.emoji) in menu_config['options'], timeout=120) except asyncio.TimeoutError: message.content = 'No reaction recieved in menu... timing out' await thread.reply(message) else: alias = menu_config['options'][str(reaction.emoji)] ctxs = [] if alias is not None: ctxs = [] aliases = normalize_alias(alias) for alias in aliases: view = StringView(self.bot.prefix + alias) ctx_ = commands.Context(prefix=self.bot.prefix, view=view, bot=self.bot, message=message) ctx_.thread = thread discord.utils.find(view.skip_string, await self.bot.get_prefix()) ctx_.invoked_with = view.get_word().lower() ctx_.command = self.bot.all_commands.get( ctx_.invoked_with) ctxs += [ctx_] for ctx in ctxs: if ctx.command: old_checks = copy.copy(ctx.command.checks) ctx.command.checks = [ checks.has_permissions(PermissionLevel.INVALID) ] await self.bot.invoke(ctx) ctx.command.checks = old_checks continue
async def invoke(self, ctx: SlashContext, command): view = StringView(command) m = await ctx.send(f"Invoking command `{command}`...") ctx = commands.Context( prefix=bot_prefix, view=view, bot=self.bot, message=m) invoker = view.get_word() ctx.invoked_with = invoker if command := self.bot.all_commands.get(invoker): # invoke a command ctx.command = command await self.bot.invoke(ctx)
async def wanted(self, ctx, member: discord.Member = None): if member is None: member = ctx.author warn_msg = 'the dagpi wanted endpoint has a flaw which makes it very slow to compute' if ctx.author.id in self.bot.owner_ids else 'This may take some time' warn = await ctx.send(warn_msg) url = str(member.avatar_url_as(format="png", size=1024)) img = await self.bot.dag.image_process(ImageFeatures.wanted(), url) try: await warn.delete() except: pass finally: await (commands.Context( prefix=ctx.prefix, message=ctx.message)).send(file=discord.File( fp=img.image, filename=f"pixel.{img.format}"))
async def on_member_ban(self, guild, user): """ Called upon a member being banned from a guild :param guild: Guild the user was banned from :param user: User who was banned """ options = self.database.get_guild_options(guild.id) if not options.mod_log: return channel = list( filter(lambda x: x.name == options.log_channel, guild.channels)) if channel: channel = channel[0] ctx = commands.Context(message=FakeMessage(guild, channel)) await self.mod_log(ctx, "ban", user, "User banned for unknown reason")
def fake_ctx(self, command, guild): if isinstance(command, str): command = getattr(self.cogs['bdaybot_commands'], command) stringview = commands.view.StringView( f'{self.parsed_command_prefix}{command.name}') message_dict = self.message_dict.copy() message_dict['content'] = f'{self.parsed_command_prefix}{command.name}' message = discord.message.Message(state='lol', channel=guild.text_channels[0], data=message_dict) return commands.Context(message=message, bot=self, prefix=self.parsed_command_prefix, invoked_with=command.name, view=stringview, command=command)
def ctx_dict(ctx=None, dict_=None): if not ctx and not dict_: return elif ctx: # turning ctx to dict return { 'message': message_dict(message=ctx.message), 'args': ctx.args, 'kwargs': ctx.kwargs, 'prefix': ctx.prefix, 'command': ctx.command, 'invoked_with': ctx.invoked_with } elif dict_: # turning dict into ctx return commands.Context(message=dict_['message'], args=dict_['args'], kwargs=dict_['kwargs'], prefix=dict_['prefix'], command=dict_['command'], invoked_with=dict_['invoked_with'])
async def run_lottery(message_id, seed=None, manual_run=False): lottery_id = Lottery.pending_lotteries[message_id]['lottery_id'] message, channel, emoji, nb_winners, time, organizer = await Lottery.get_message_env( lottery_id) try: players, reaction, winners = await Lottery.draw( message, emoji, nb_winners, seed) await reaction.remove(zbot.bot.user) await Lottery.announce_winners(winners, players, message, organizer) Lottery.remove_pending_lottery(message_id, cancel_job=manual_run) except commands.CommandError as error: context = commands.Context( bot=zbot.bot, cog=Lottery, prefix=zbot.bot.command_prefix, channel=channel, message=message, ) await error_handler.handle(context, error)
async def run_tests_and_quit(): # ignore this; it is purely for the benefit of being able to run the examples as tests. import sys class Msg: _state = bot._connection await bot.wait_until_ready() ctx = commands.Context(prefix=None, message=Msg, bot=bot) async def _mock_get_channel(): return bot.get_channel(INFO_CHANNEL_ID) ctx._get_channel = _mock_get_channel await ctx.invoke(player_heroes, "#JY9J2Y99") for command in (clan_info, clan_member, current_war_status): await ctx.invoke(command, clan_tags[0]) sys.exit(0)
async def close_poll(message_id, manual_run=False): poll_id = Poll.pending_polls[message_id]['poll_id'] message, channel, emoji_list, is_exclusive, required_role_name, time, organizer = \ await Poll.get_message_env(poll_id) try: reactions, results = await Poll.count_votes( message, emoji_list, is_exclusive, required_role_name) for reaction in reactions: await reaction.remove(zbot.bot.user) await message.unpin() await Poll.announce_results(results, message, channel, is_exclusive, required_role_name, organizer) Poll.remove_pending_poll(message_id, cancel_job=manual_run) except commands.CommandError as error: context = commands.Context( bot=zbot.bot, cog=Poll, prefix=zbot.bot.command_prefix, channel=channel, message=message, ) await error_handler.handle(context, error)
async def _run_command(self, message): if not message.content.startswith(self.command_prefix): return ctx = _commands.Context(prefix=self.command_prefix, bot=self, message=message, args=message.content.split(" ")[1:]) if not ctx.channel.permissions_for(ctx.me).send_messages: return # what's the point of running a command if the bot doesn't have the perms to send messages kekw try: command_name = message.content[len(self.command_prefix):].split( )[0] ctx.command = self.all_commands[command_name.lower()] if not await ctx.command.can_run(ctx): return if ctx.command._max_concurrency: await ctx.command._max_concurrency.acquire(ctx) try: ctx.command._prepare_cooldowns(ctx) except: if ctx.command._max_concurrency: await ctx.command._max_concurrency.release(ctx) raise await _hooked_wrapped_callback(ctx.command, ctx, ctx.command.callback)() except (KeyError, IndexError): return except Exception as exc: self.dispatch("command_error", ctx, exc, format_exc()) else: self.command_uses += 1 del ctx, command_name
async def on_reaction_add(self, reaction, user): """ check if users clicked the play button on executable code the bot has to be a reactor on the executable message """ message = reaction.message if not self.is_evaluatable_message(message.content): return if message.author.bot or user.bot or message.author != user: return if str(reaction.emoji) != "▶": return if self.bot.user not in await reaction.users().flatten(): return ctx = commands.Context(prefix=self.bot.command_prefix, guild=message.guild, channel=message.channel, message=message, author=user) await self._eval.callback(self, ctx, body=message.content)
async def start(self): self.msg = await self.channel.send(content=self.author.mention, embed=self.startembed) await self.msg.add_reaction("📝") await self.msg.add_reaction("🗑️") def check(payload): return payload.user_id == self.author.id and payload.message_id == self.msg.id and ( str(payload.emoji) == "📝" or str(payload.emoji) == '🗑️') try: payload = await self.client.wait_for('raw_reaction_add', check=check, timeout=7000) # Wait except asyncio.TimeoutError: if self.author.id in self.client.raid_db[self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't log this run in time!", color=discord.Color.red()) try: await self.msg.clear_reactions() return await self.msg.edit(embed=embed) except discord.NotFound: print("NOT FOUND WHEN LOGGING AWAIT") return else: if str(payload.emoji) == '🗑️': if self.author.id in self.client.raid_db[ self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Cancelled!", description=f"{self.author.mention} cancelled this log.", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) # Log rune pops if self.run_title == "Oryx 3" or self.run_title == 'Vet Oryx 3': desc = "" descript = "" if '<:swordrune:737672554482761739>' in self.required_items: swordreacts = self.required_items[ '<:swordrune:737672554482761739>']['confirmed'] if swordreacts: for i, r in enumerate(swordreacts): desc += self.numbers[i] + f" - {r.mention}\n" descript = f"Users who confirmed sword rune (<:swordrune:737672554482761739>) with the bot:\n" + desc + "\n" descript += "Click the 🔄 to enter who popped. If you don't know, hit the ❌." embed = discord.Embed(title="Sword Rune Pop", description=descript, color=discord.Color.gold()) await self.memberlog(embed, swordreacts, sql.log_cols.swordrunes, '<:swordrune:737672554482761739>') desc = "" descript = "" if '<:shieldrune:737672554642276423>' in self.required_items: shieldreacts = self.required_items[ '<:shieldrune:737672554642276423>']['confirmed'] if shieldreacts: for i, r in enumerate(shieldreacts): desc += self.numbers[i] + f" - {r.mention}\n" descript = f"Users who confirmed shield rune (<:shieldrune:737672554642276423>) with the bot:\n" + desc + "\n" descript += "Click the 🔄 to enter who popped. If you don't know, hit the ❌." embed = discord.Embed(title="Shield Rune Pop", description=descript, color=discord.Color.gold()) await self.memberlog(embed, shieldreacts, sql.log_cols.shieldrunes, '<:shieldrune:737672554642276423>') desc = "" descript = "" if '<:helmrune:737673058722250782>' in self.required_items: helmreacts = self.required_items[ '<:helmrune:737673058722250782>']['confirmed'] if helmreacts: for i, r in enumerate(helmreacts): desc += self.numbers[i] + f" - {r.mention}\n" descript = f"Users who confirmed helm rune (<:helmrune:737673058722250782>) with the bot:\n" + desc + "\n" descript += "Click the 🔄 to enter who popped. If you don't know, hit the ❌." embed = discord.Embed(title="Helm Rune Pop", description=descript, color=discord.Color.gold()) await self.memberlog(embed, helmreacts, sql.log_cols.helmrunes, '<:helmrune:737673058722250782>') embed = discord.Embed( title=f"Member Completion: {self.author.display_name}", description= "Please send a screenshot containing **only** the /who of members which " "completed the raid.\n\nIf you don't have a screenshot and a raider cannot take one either - send `SKIP`" ) await self.msg.clear_reactions() await self.msg.edit(embed=embed) def member_check(m): return m.author == self.author and m.channel == self.channel members = [] while True: try: msg = await self.client.wait_for('message', timeout=7200, check=member_check) except asyncio.TimeoutError: if self.author.id in self.client.raid_db[ self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't choose a member in time!", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) if 'skip' in msg.content.strip().lower(): print('skipped') await self.channel.send( f"{self.author.mention} Skipped uploading a screenshot. Please take a screenshot of /who next run so we can track accurate stats." ) members = self.members_left break else: if not msg.attachments: await self.channel.send( "Please attach an image containing only the result of the /who command!", delete_after=10) continue if len(msg.attachments) > 1: await self.channel.send("Please only attach 1 image.", delete_after=10) continue attachment = msg.attachments[0] if not ".jpg" in attachment.filename and not ".png" in attachment.filename: await self.channel.send( "Please only attach an image of type 'png' or 'jpg'.", delete_after=10) continue image = io.BytesIO() await attachment.save(image, seek_begin=True) pmsg = await self.channel.send( "Parsing image. This may take a minute...") members = await self.client.loop.run_in_executor( None, functools.partial(parse_image, image, self.all_members)) print('done parsing image') await pmsg.delete() if not members: embed = discord.Embed( title="Error!", description= "Could not find the /who command in the image you provided.\nPlease send a new message" "with an image that shows the results of `/who`. If you don't have a better image, say `SKIP`.", color=discord.Color.red()) await self.channel.send(embed=embed, delete_after=15) await msg.delete() continue converter = utils.MemberLookupConverter() _mems = [] ctx = commands.Context(bot=self.client, prefix="!", guild=self.guild, message=msg) for n in members: try: m = await converter.convert(ctx, n) _mems.append(m) except discord.ext.commands.BadArgument: pass members = _mems embed = discord.Embed( title=f"Member Completion: {self.author.display_name}", description="Please enter who took this screenshot.") await self.msg.edit(embed=embed) def member_check(m): return m.author == self.author and m.channel == self.channel while True: try: msg = await self.client.wait_for('message', timeout=7200, check=member_check) except asyncio.TimeoutError: if self.author.id in self.client.raid_db[ self.guild.id]['leaders']: self.client.raid_db[ self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't choose a member in time!", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) try: ctx = commands.Context(bot=self.client, prefix="!", guild=self.guild, message=msg) mem = await converter.convert(ctx, msg.content.strip()) members.append(mem) break except discord.ext.commands.BadArgument: await self.channel.send( f"The member you specified (`{msg.content}`) was not found.", delete_after=7) continue break await msg.delete() await self.msg.clear_reactions() await self.msg.edit(embed=self.runstatusembed) await self.msg.add_reaction("✅") await self.msg.add_reaction("❌") def check(payload): return payload.user_id == self.author.id and payload.message_id == self.msg.id and ( str(payload.emoji) == "✅" or str(payload.emoji) == "❌") try: payload = await self.client.wait_for('raw_reaction_add', timeout=7200, check=check) # Wait 1 hr max except asyncio.TimeoutError: if self.author.id in self.client.raid_db[self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't log this run in time!", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) col = sql.log_cols.srunled if str( payload.emoji) == "✅" else sql.log_cols.frunled await sql.log_runs(self.client.pool, self.guild.id, self.author.id, col, 1) self.confirmedLogs.append(("Run Successful", str(payload.emoji))) embed = discord.Embed( title="Logging...", description="Please wait while the run is logged in the database. " "This can take up to a minute at full run capacity.", color=discord.Color.orange()) embed.set_thumbnail(url="https://i.imgur.com/nLRgnZf.gif") await self.msg.clear_reactions() await self.msg.edit(content=None, embed=embed) print(members) members.append(self.author) for m in members: print(type(m)) print(m) if m.top_role >= self.rlrole: print('logging rl') await sql.log_runs(self.client.pool, self.guild.id, m.id, sql.log_cols.runsassisted, 1) await sql.log_runs(self.client.pool, self.guild.id, m.id, sql.log_cols.ocompletes, 1) print('done logging 1') attempted = 0 print(self.all_members) attempted_members = [m for m in self.all_members if m not in members] print(type(attempted_members)) if attempted_members: for m in attempted_members: attempted += 1 await sql.log_runs(self.client.pool, self.guild.id, m.id, sql.log_cols.oattempts, 1) print('done logging 2') desc = "Log Status:\n" for r in self.confirmedLogs: desc += r[0] + " - " + str(r[1]) + "\n" desc += "Run Leader - " + self.author.mention + "\n" desc += f"# Raiders Failed - {attempted}\n" desc += f"# Raiders Completed - {len(members)}\n" # try: # desc += str(self.confirmedLogs[-1][0]) + " - " + str(self.confirmedLogs[-1][1]) # except IndexError: # pass if self.author.id in self.client.raid_db[self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed(title="Run Logged!", description=desc, color=discord.Color.green()) await self.msg.edit(embed=embed)
async def memberlog(self, embed, reacts, column, emoji): await self.msg.clear_reactions() await self.msg.edit(embed=embed) emojis = [] if reacts: if len(reacts) > 5: reacts = reacts[:5] emojis = self.numbers[:len(reacts)] emojis.append("🔄") emojis.append("❌") asyncio.get_event_loop().create_task(self.add_emojis(self.msg, emojis)) def check(payload): return payload.user_id == self.author.id and payload.message_id == self.msg.id and str( payload.emoji) in emojis try: payload = await self.client.wait_for('raw_reaction_add', timeout=7000, check=check) # Wait ~2 hr max except asyncio.TimeoutError: if self.author.id in self.client.raid_db[self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't log this run in time!", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) if str(payload.emoji) == '❌': return elif str(payload.emoji) in self.numbers: i = self.numbers.index(str(payload.emoji)) member = reacts[i] if isinstance(member, str): member = self.client.get_user(int(member)) else: await self.msg.clear_reactions() self.otheremebed.title = f"Log Other member {self.author.display_name} for {emoji}" await self.msg.edit(embed=self.otheremebed) def member_check(m): return m.author == self.author and m.channel == self.channel while True: try: msg = await self.client.wait_for('message', timeout=7200, check=member_check) except asyncio.TimeoutError: if self.author.id in self.client.raid_db[ self.guild.id]['leaders']: self.client.raid_db[self.guild.id]['leaders'].remove( self.author.id) embed = discord.Embed( title="Timed out!", description="You didn't choose a member in time!", color=discord.Color.red()) await self.msg.clear_reactions() return await self.msg.edit(embed=embed) try: ctx = commands.Context(bot=self.client, prefix="!", guild=self.guild, message=msg) member = await self.converter.convert( ctx, str(msg.content)) try: await msg.delete() except discord.NotFound: pass break except discord.ext.commands.BadArgument: await self.channel.send( f"The member you specified (`{msg.content}`) was not found.", delete_after=7) num = await sql.log_runs(self.client.pool, self.guild.id, member.id, column, 1) # if emoji == self.emojis[1] and not self.events and str(emoji) != '<:WineCellarInc:708191799750950962>': # await utils.check_pops(self.client, member, self.numruns, num, guild=self.guild, emoji=emoji, type='key', hcchannel=self.hcchannel) if emoji == "<:helmrune:737673058722250782>": await utils.check_pops(self.client, member, 1, num, guild=self.guild, emoji=emoji, type='helm', hcchannel=self.hcchannel) elif emoji == "<:shieldrune:737672554642276423>": await utils.check_pops(self.client, member, 1, num, guild=self.guild, emoji=emoji, type='shield', hcchannel=self.hcchannel) elif emoji == "<:swordrune:737672554482761739>": await utils.check_pops(self.client, member, 1, num, guild=self.guild, emoji=emoji, type='sword', hcchannel=self.hcchannel) # elif emoji == "<:vial:682205784524062730>": # await utils.check_pops(self.client, member, self.numruns, num, guild=self.guild, emoji=emoji, type='vial', hcchannel=self.hcchannel) self.confirmedLogs.append((emoji, f"{member.mention}"))
async def on_message(self, message): # Event triggers when message is sent """Runs whenever a message is sent""" if not lbvars.bot_is_ready: return # Prevent the bot from activating from other bots if message.author.bot: return guild = message.guild if guild is None: guild = message.channel guild_id = str(guild.id) prefix = lbvars.get_prefix(guild_id) msg_raw = message.content msg = msg_raw.lower() ctx = commands.Context(message=message, bot=self.bot, prefix=prefix) async def replace_ass(): # Sends the ass substitution message await self.bot.get_command("replaceass").invoke(ctx) lbvars.set_last_use_time(time.time()) if message.guild is None: lbvars.LOGGER.info("DM from %s: %s", message.author, message.content) if message.author.id == 309480972707954688: await message.channel.send("Hey, babe, what's up? :smirk:") if "help" in message.content: await self.bot.get_command("help").invoke(ctx) elif "lmao" in message.content or "lmfao" in message.content: await replace_ass() else: await self.bot.get_command("info").invoke(ctx) lbvars.set_last_use_time(time.time()) return # If used by bot's creator, displays last time a lmao-bot command was used # DEV NOTE: This is expensive and there are better ways to handle this then running an if statement for every message. # if perms.is_lmao_developer(ctx.message) and message.content.lower().strip() == "last command used": # current_time = time.time() # await message.channel.send(f"The last command was used {lbutil.eng_time(current_time - lbvars.get_last_use_time())} ago.") #COMMANDS if self.starts_with_prefix( message): # Bot reacts to command prefix call if message.content.startswith(self.bot.user.mention): prefix = self.bot.user.mention else: prefix = lbvars.get_prefix(guild_id) msg_no_prefix = message.content[len(prefix):].strip() words = msg_no_prefix.split() cmd_name = "" if len(words) > 0: cmd_name = words[0] # lbvars.import_settings() if cmd_name.lower() in self.get_all_commands(): await self.bot.process_commands(message) else: try: await message.channel.send( perms.clean_everyone( ctx, lbvars.get_custom_cmd_list( message.guild.id)[cmd_name].strip())) except KeyError: if "lmao" in message.content.lower( ) or "lmfao" in message.content.lower(): await replace_ass() if not lbvars.get_no_command_invoked(): lbvars.set_last_use_time(time.time()) lbvars.set_no_command_invoked(False) lbvars.export_settings(guild_id) elif msg == "lmao help": await message.channel.send( f"Type `{prefix} help` to see the help menu.") elif msg == "lmao prefix": await message.channel.send( f"My command prefix for {message.guild.name} is currently `{prefix}`." ) # GENERIC REPLY elif ("lmao" in msg or "lmfao" in msg): #generic ass substitution await replace_ass() lbvars.export_settings(guild_id) #FILTERS else: filters = lbvars.get_filter_list(guild_id) for key, value in filters.items(): flags = value["flags"] if "chance" in flags: chance = lbutil.parse_chance(flags) x = random.randint(1, 100) if x > chance: continue needle = key.lower() haystack = ctx.message.content.lower() if "casesensitive" in flags: needle = key haystack = ctx.message.content if "wholeword" in flags: haystack = haystack.split() contains_key = needle in haystack if contains_key: mention = f"{message.author.mention} " if "nomention" in flags: mention = "" await ctx.send( perms.clean_everyone(ctx, f"{mention}{value['message']}")) lbvars.export_settings(guild_id) if guild_id in ["345655060740440064", "407274897350328345" ] and ("pollard" in msg or "buh-bye" in msg or "buhbye" in msg or "buh bye" in msg): emoji_list = self.bot.get_guild(345655060740440064).emojis for emoji in emoji_list: if emoji.name == "buhbye": buhbye = emoji try: await message.add_reaction(buhbye) except UnboundLocalError: pass except discord.errors.Forbidden: pass
async def ctx(bot, command): message = await dpytest.message("dummy") ctx = commands.Context(bot=bot, message=message, prefix="dummy") ctx.command = command return ctx
async def on_reaction_add(self, reaction, user): # Ignore own reactions if user == self.bot.user: return # Ignore messages not sent by the bot if reaction.message.author != self.bot.user: return # Create a discord context to pass onto commands ctx = commands.Context( message = reaction.message, bot = self.bot, prefix = ";", guild = user.guild, author = user ) # Get the music player player = await self.get_player(ctx) # -- NOW PLAYING CONTROLS -- # QUEUE # -- NOW PLAYING CONTROLS -- # QUEUE if reaction.emoji in '🇶': await self.queue.callback(self, ctx) # pylint: disable=no-member # PLAY (RESUME) elif reaction.emoji in '▶': await self.resume.callback(self, ctx) # pylint: disable=no-member # PAUSE elif reaction.emoji in '⏸': await self.pause.callback(self, ctx) # pylint: disable=no-member # SHUFFLE elif reaction.emoji in '🔀': await self.shuffle.callback(self, ctx) # pylint: disable=no-member # SKIP elif reaction.emoji in '⏭': await self.skip.callback(self, ctx) # pylint: disable=no-member # STOP elif reaction.emoji in '⏹': await self.stop.callback(self, ctx) # pylint: disable=no-member # VOLUME elif reaction.emoji in '🔊': await self.volume.callback(self, ctx) # pylint: disable=no-member # -- VOLUME CONTROLS -- elif reaction.emoji in '⬇️': # volume down await player.set_volume(volume=player.volume - 1.75) await player.update_volume_message(user=user) elif reaction.emoji in '⬆️': # volume up await player.set_volume(volume=player.volume + 1.75) await player.update_volume_message(user=user) elif reaction.emoji in '⏬': # volume down+ await player.set_volume(volume=player.volume - 8) await player.update_volume_message(user=user) elif reaction.emoji in '⏫': # volume up+ await player.set_volume(volume=player.volume + 8) await player.update_volume_message(user=user) elif reaction.emoji in '✳': # volume reset await player.set_volume(volume=20) await player.update_volume_message(user=user) else: # Unknown emoji, do nothing return # Remove the reaction once the job is done try: await reaction.remove(user) except discord.errors.NotFound: pass