async def on_command_error(error, ctx): msg = ctx.message if isinstance(error, commands.NoPrivateMessage): await bot.send_message( msg.author, formatter.error('This command cannot be used in private messages.') ) elif isinstance(error, commands.DisabledCommand): await bot.send_message( msg.channel, formatter.error( 'Sorry. This command is disabled and cannot be used.')) elif isinstance(error, commands.CommandInvokeError): await bot.send_message( msg.channel, formatter.error('Command error: {}'.format(error))) elif isinstance(error, commands.errors.CheckFailure): await bot.send_message( msg.channel, formatter.error( 'Sorry you have insufficient permissions to run that command.') ) else: await bot.send_message(msg.channel, formatter.error(str(error))) e_tb = traceback.format_exception(error.__class__, error, error.__traceback__) lines = [] for line in e_tb: lines.extend(line.rstrip('\n').splitlines()) logger.error(f'<{msg.author.name}> {msg.content}: %s', '\n'.join(lines))
async def on_command_error(error, ctx): if isinstance(error, commands.NoPrivateMessage): await bot.send_message( ctx.message.author, formatter.error('This command cannot be used in private messages.') ) elif isinstance(error, commands.DisabledCommand): await bot.send_message( ctx.message.channel, formatter.error( 'Sorry. This command is disabled and cannot be used.')) elif isinstance(error, commands.CommandInvokeError): logger.error('In {0.command.qualified_name}:'.format(ctx)) logger.error(error.original.__traceback__) logger.error('{0.__class__.__name__}: {0}'.format(error.original)) await bot.send_message( ctx.message.channel, formatter.error('Command error: {}'.format(error))) elif isinstance(error, commands.errors.CheckFailure): await bot.send_message( ctx.message.channel, formatter.error( 'Sorry you have insufficient permissions to run that command.') ) else: await bot.send_message(ctx.message.channel, formatter.error(str(error)))
async def meme(self, ctx, *, text: str): """ Adds text to images Valid names so far: """ match = MemeGenerator.pattern.match(text) name = match.group(1).lower() text = match.group(2) text = ' '.join(dh.remove_comments(text.split())) cfg = self.conf.get('memes', {}).get(name, None) if not cfg: await self.bot.say(error('Could not find image')) return if not text: await self.bot.say(error('Are you trying to get an empty image?')) return temp = tempfile.NamedTemporaryFile(suffix=".png") if 'font' not in cfg: cfg['font'] = self.conf.get('font', '') if 'path' not in cfg: cfg['path'] = self.conf.get('path', '') write_image(text, temp.name, **cfg) await self.bot.send_file(ctx.message.channel, temp.name) temp.close()
async def nsfw(self, ctx): """NSFW stuff""" channel = ctx.message.channel if not channel.is_private and 'nsfw' not in channel.name.lower(): await self.bot.say(formatter.error('not in nsfw channel')) ctx.invoked_subcommand = None return if ctx.invoked_subcommand is None: await self.bot.say( formatter.error("Please specify valid subcommand")) return
async def nsfw(self, ctx): """NSFW stuff""" channel = ctx.message.channel # ensure that the current channel is marked as nsfw if not channel.is_private and 'nsfw' not in channel.name.lower(): await self.bot.say(formatter.error('not in nsfw channel')) ctx.invoked_subcommand = None return # if user misstyped or does not know what they are doing, complain if ctx.invoked_subcommand is None: await self.bot.say( formatter.error("Please specify valid subcommand")) return
async def add_groupme_link(self, ctx, g_id: str): channel = ctx.message.channel group, g_bot = self.get_group_bot(g_id) if not group: await self.bot.say( formatter.error("I am not in a group with that id")) return if g_id not in self.g_groups: self.l_bots.append(g_bot) self.g_groups[g_id] = group if channel.id in self.g_bots: self.g_bots[channel.id].append(g_bot) self.conf['links'][channel.id].append(g_id) else: self.g_bots[channel.id] = [g_bot] self.conf['links'][channel.id] = [g_id] if g_id in self.d_chans: self.d_chans[g_id].append(channel) else: self.d_chans[g_id] = [channel] if g_id not in self.g_groups: self.conf['g_old'][g_id] = None self.conf.save() await self.bot.say(formatter.ok())
async def _search(self, ctx, *, query: str): """searches for query on emby, displays first result if first "word" in query is a number, returns that many results (ignoring the number) """ match = re.search(r'^(\d)+\s+(\S.*)$', query) if not query: await self.bot.say(formatter.error('missing query')) return elif match: num = int(match.group(1)) query = match.group(2) else: num = 1 results = await self.loop.run_in_executor(None, self.conn.search, query) results = [i for i in results if issubclass(type(i), EmbyObject)] if not results: await self.bot.say('No results found') return for result in results[:num]: await self.loop.run_in_executor(None, result.update) em = await emby_helper.makeEmbed(result) await self.bot.send_message(ctx.message.channel, embed=em)
async def rep(self, ctx): """Manage replacements Uses a regex to replace text from users """ if ctx.invoked_subcommand is None: await self.bot.say( formatter.error( 'Error, {0.subcommand_passed} is not a valid command'. format(ctx)))
async def _edit(self, ctx, *, regex): """edits an existing replacement Format `s/old/new/` """ #Find requested replacement rep = get_match(regex) #ensure that replace was found before proceeding if not rep: await self.bot.say(formatter.error('Could not find valid regex')) return p1 = formatter.escape_mentions(rep.group(2)) p2 = formatter.escape_mentions(rep.group(4)) #check regex for validity if not comp(p1, p2): await self.bot.say(formatter.error('regex is invalid')) return #make sure regex is not too broad if bad_re(p1): await self.bot.say(formatter.error('regex is too broad')) return #ensure that replace was found before proceeding if p1 not in self.replacements: await self.bot.say(formatter.error('Regex not in replacements.')) return #check if they have correct permissions if ctx.message.author.id != self.replacements[p1][1] \ and not perms.is_owner_check(ctx.message): #will uncomment next line when reps are a per server thing #and not perms.check_permissions(ctx.message, manage_messages=True): raise commands.errors.CheckFailure('Cannot edit') self.replacements[p1] = [p2, ctx.message.author.id] await self.bot.say(formatter.ok())
async def _td_remove(self, ctx, *, index : int): ''' remove a task from your todo list Note: indicies start at 1 ''' todos = self.conf['todo'].get(ctx.message.author.id, []) if len(todos) < index or index <= 0: await self.bot.say(formatter.error('Invalid index')) else: task = todos.pop(index - 1) self.conf['todo'][ctx.message.author.id] = todos self.conf.save() await self.bot.say(formatter.ok('Removed task #{}'.format(index)))
async def _td_done(self, ctx, *, index : int): ''' sets/unsets a task as complete Note: indicies start at 1 ''' todos = self.conf['todo'].get(ctx.message.author.id, []) if len(todos) < index or index <= 0: await self.bot.say(formatter.error('Invalid index')) else: index -= 1 todos[index][0] = not todos[index][0] self.conf['todo'][ctx.message.author.id] = todos self.conf.save() await self.bot.say(formatter.ok())
async def _rm(self, ctx, index: int): """remove an existing replacement by index""" if index >= len(self.quotes_dict['quotes']): await self.bot.say( formatter.error('Quote {} does not exist'.format(index))) return if ctx.message.author.id != self.quotes_dict['quotes'][index]['id'] \ and not perms.check_permissions(ctx.message, manage_messages=True): raise commands.errors.CheckFailure('Cannot delete') self.quotes_dict['quotes'].pop(index) self.quotes_dict.save() await self.bot.say(formatter.ok())
async def quotes(self, ctx): """Manage quotes""" if ctx.invoked_subcommand is None: message = ctx.message.content try: index = int(ctx.subcommand_passed) if index >= len(self.quotes_dict['quotes']): await self.bot.say( formatter.error( 'Quote {} does not exist'.format(index))) else: quote = self.quotes_dict['quotes'][index] message = 'On {}:\n{}'.format( quote['date'], formatter.code(quote['quote'])) await self.bot.say(message) except: await self.bot.say(self._random(message))
async def _add(self, ctx, *, quote): """adds a quote""" for i in self.quotes_dict['quotes']: if quote.lower() == i['quote'].lower(): await self.bot.say(formatter.error('Quote already exists')) return index = len(self.quotes_dict['quotes']) date = datetime.now().strftime('%Y-%m-%d %H:%M:%S') self.quotes_dict['quotes'].append({ 'date': date, 'quote': quote, 'id': ctx.message.author.id }) self.quotes_dict.save() await self.bot.say(formatter.ok('quote added, index {}'.format(index)))
def _random(self, message): quotes = self.quotes_dict['quotes'] message = message.split()[1:] if message: quotes = [] for quote in self.quotes_dict['quotes']: ok = True for w in message: if w.lower() not in quote['quote'].lower(): ok = False break if ok: quotes.append(quote) if not quotes: return formatter.error('No quotes found') quote = random.choice(quotes) return 'On {}:\n{}'.format(quote['date'], formatter.code(quote['quote']))
async def _add(self, ctx, *, regex): """adds a new replacement Format `s/old/new/` """ if ctx.message.author.id in self.permissions['rep-blacklist']: await self.bot.say(formatter.error('No ') + ':poi:') return #Find requested replacement rep = get_match(regex) #ensure that replace was found before proceeding if not rep: await self.bot.say(formatter.error('Could not find valid regex')) return p1 = formatter.escape_mentions(rep.group(2)) p2 = formatter.escape_mentions(rep.group(4)) #check regex for validity if not comp(p1, p2): await self.bot.say(formatter.error('regex is invalid')) return #make sure that there are no similar regexes in db for i in self.replacements: if similar(p1, i): r = '\"{}\" -> \"{}\"'.format(i, self.replacements[i][0]) message = 'Similar regex already exists, delete or edit it\n{}'.format( formatter.inline(r)) await self.bot.say(formatter.error(message)) return #make sure regex is not too broad if bad_re(p1): await self.bot.say(formatter.error('regex is too broad')) return #check that regex does not already exist if p1 in self.replacements: await self.bot.say(formatter.error('regex already exists')) return self.replacements[p1] = [p2, ctx.message.author.id] await self.bot.say(formatter.ok())
async def _rm(self, ctx, *, pattern): """remove an existing replacement""" #pattern = re.sub('^(`)?\\(\\?[^\\)]*\\)', '\\1', pattern) pattern = formatter.escape_mentions(pattern) #ensure that replace was found before proceeding if pattern not in self.replacements: if re.search('^`.*`$', pattern) and pattern[1:-1] in self.replacements: pattern = pattern[1:-1] else: await self.bot.say( formatter.error('Regex not in replacements.')) return #check if they have correct permissions if ctx.message.author.id != self.replacements[pattern][1] \ and not perms.is_owner_check(ctx.message): raise commands.errors.CheckFailure('Cannot delete') self.replacements.pop(pattern) self.replacements.save() await self.bot.say(formatter.ok())
async def _osu(self, ctx): """ manages osu stuff """ if ctx.invoked_subcommand is None: await self.bot.say(formatter.error("Please specify valid subcommand"))