Exemple #1
0
 async def on_error(self, ev_name, *ev_args, **ev_kwargs):
     kw_args = ', ' + (', '.join(
         [k + '=' + str(ev_kwargs[k])
          for k in ev_kwargs])) if ev_kwargs else ''
     self.logger.error(f'Event handler {ev_name} errored! Called with ' +
                       (', '.join([bdel(str(i), 'Command raised an exception: ') \
                       for i in ev_args]) if ev_args else 'nothing') + kw_args)
     self.logger.error(traceback.format_exc())
Exemple #2
0
    async def deref(self, ctx, *, code: str):
        """Evaluate some code in command scope.
        Usage: deref [code to execute]"""
        if ctx.message.author.id != '160567046642335746':
            await self.bot.say('No permission!')
            return False

        def print(*ina: str):
            self.loop.create_task(self.bot.say(' '.join(ina)))
            return True

        try:
            ev_output = eval(bdel(bdel(code, '```python'), '```py').strip('`'))
        except Exception as e:
            ev_output = 'An exception of type %s has occured!\n' % type(
                e).__name__ + str(e)
        o = str(ev_output)
        await self.bot.say('```py\n' + o + '```')
Exemple #3
0
 async def seref(self, ctx, *, code: str):
     """Evaluate some code (multi-statement) in command scope.
     Usage: seref [code to execute]"""
     echeck_perms(ctx, ('bot_owner',))
     dc = self.dc_funcs
     def print(*ina: str):
         self.loop.create_task(self.bot.say(' '.join(ina)))
         return True
     try:
         ev_output = exec(bdel(bdel(code, '```python'), '```py').strip('`'))
     except Exception as e:
         ev_output = 'An exception of type %s occured!\n' % type(e).__name__ + str(e)
     o = str(ev_output)
     if ev_output is None:
         await self.bot.say('✅')
         return
     if ctx.invoked_with.startswith('r'):
         await self.bot.say(o)
     else:
         await self.bot.say('```py\n' + o + '```')
Exemple #4
0
 async def auto_cb_convo(self, msg, kickstart, replace=False):
     """Cleverbot auto conversation manager."""
     if self.bot.status == 'invisible': return
     await self.bot.send_typing(msg.channel)
     lmsg = msg.content.lower().replace('@everyone', 'everyone').replace('@here', 'here')
     for m in msg.mentions:
         lmsg = lmsg.replace(m.mention, m.display_name)
     if replace:
         cb_string = lmsg.replace(kickstart, '')
     else:
         cb_string = bdel(lmsg, kickstart)
     reply_bot = await self.askcb(cb_string)
     await self.bot.msend(msg, msg.author.mention + ' ' + reply_bot)
Exemple #5
0
    async def on_command_error(self, exp, ctx):
        try:
            myself = ctx.message.server.me
        except AttributeError:
            myself = self.bot.user
        if not myself:
            myself = self.bot.user
        if self.bot.selfbot:
            try:
                cmdfix = self.store['properties']['global']['selfbot_prefix']
            except KeyError:
                cmdfix = myself.name[0].lower() + '.'
        else:
            cmdfix = self.store.get_cmdfix(ctx.message)
        cproc = ctx.message.content.split()[0]
        cprocessed = bdel(cproc, cmdfix)
        c_key = str(exp)
        bc_key = bdel(c_key, 'Command raised an exception: ')
        eprefix = 's'
        try:
            cmid = ctx.message.server.id
        except AttributeError:
            cmid = ctx.message.author.id
            eprefix = 'dm'
        if ctx.message.server:
            location = ctx.message.server.name
        else:
            location = '[DM with %s]' % str(ctx.message.author)
        if isinstance(exp, commands.CommandNotFound):
            self.logger.error(str(ctx.message.author) + ' in ' + location + ': command \'' + cprocessed + '\' not found')
        elif isinstance(exp, commands.CommandInvokeError):
            self.logger.error(str(ctx.message.author) + ' in ' + location + f': [cmd {cprocessed}] ' + bc_key)
            self.logger.error('Traceback (most recent call last):\n' + ''.join(traceback.format_tb(exp.original.__traceback__)) \
                              + type(exp.original).__name__ + ': ' + str(exp.original))
        elif isinstance(exp, commands.CommandPermissionError) or isinstance(exp, commands.OrCommandPermissionError):
            self.logger.error(str(ctx.message.author) + ' in ' + location + f': Not enough permissions for ' + ctx.message.content[:150])
        elif isinstance(exp, commands.MissingRequiredArgument) or \
             isinstance(exp, commands.BadArgument) or isinstance(exp, commands.TooManyArguments):
            self.logger.error(str(ctx.message.author) + ' in ' + location + f': [cmd {cprocessed}] Argument error. ' + str(exp))
        else:
            self.logger.error(str(ctx.message.author) + ' in ' + location + f': [cmd {cprocessed}] ' + str(exp) + ' (%s)' % type(exp).__name__)
            self.logger.error('Traceback (most recent call last):\n' + ''.join(traceback.format_tb(exp.__traceback__)) \
                              + type(exp).__name__ + ': ' + str(exp))

        if isinstance(exp, commands.NoPrivateMessage):
            await self.csend(ctx, npm_fmt.format(ctx.message.author, cprocessed, cmdfix))
        elif isinstance(exp, commands.CommandNotFound):
            pass
        elif isinstance(exp, commands.DisabledCommand):
            await self.csend(ctx, ccd_fmt.format(ctx.message.author, cprocessed, cmdfix))
        elif isinstance(exp, commands.CommandOnCooldown) or isinstance(exp, DiscordCNC):
            await self.csend(ctx, ':warning: :gear: ' + random.choice(clocks))
        elif isinstance(exp, commands.PassException):
            pass
        elif isinstance(exp, commands.ReturnError):
            await self.csend(ctx, exp.text)
        elif isinstance(exp, commands.CommandPermissionError):
            _perms = ''
            if exp.perms_required:
                perm_list = [i.lower().replace('_', ' ').title() for i in exp.perms_required]
                if len(perm_list) > 1:
                    perm_list[-1] = '**and **' + perm_list[-1] # to cancel bold
                _perms = ', '.join(perm_list)
            else:
                _perms = 'Not specified'
            await self.csend(ctx, cpe_fmt.format(ctx.message.author, cprocessed, cmdfix, _perms))
        elif isinstance(exp, commands.OrCommandPermissionError):
            _perms = ''
            if exp.perms_ok:
                perm_list = [i.lower().replace('_', ' ').title() for i in exp.perms_ok]
                if len(perm_list) > 1:
                    perm_list[-1] = '**or **' + perm_list[-1] # to cancel bold
                _perms = ', '.join(perm_list)
            else:
                _perms = 'Not specified'
            await self.csend(ctx, ocpe_fmt.format(ctx.message.author, cprocessed, cmdfix, _perms))
        elif isinstance(exp, commands.CommandInvokeError):
            if isinstance(exp.original, discord.HTTPException):
                key = bdel(bc_key, 'HTTPException: ')
                if key.startswith('BAD REQUEST'):
                    key = bdel(bc_key, 'BAD REQUEST')
                    if key.endswith('Cannot send an empty message'):
                        await self.csend(ctx, emp_msg.format(ctx.message.author, cprocessed, cmdfix))
                    elif c_key.endswith('BAD REQUEST (status code: 400)'):
                        if (eprefix == 'dm') and (ctx.command.name == 'user'):
                            await self.csend(ctx, '**No matching users, try again! Name, nickname, name#0000 (discriminator), or ID work. Spaces do, too!**')
                        else:
                            await self.csend(ctx, big_msg.format(ctx.message.author, cprocessed, cmdfix))
                    else:
                        await self.csend(ctx, msg_err.format(ctx.message.author, cprocessed, cmdfix, key))
                elif c_key.startswith('Command raised an exception: HTTPException: BAD REQUEST (status code: 400)'):
                    await self.csend(ctx, big_msg.format(ctx.message.author, cprocessed, cmdfix))
                elif c_key.startswith('Command raised an exception: RuntimeError: PyNaCl library needed in order to use voice'):
                    await self.csend(ctx, '**The bot owner hasn\'t enabled voice!**')
                else:
                    await self.csend(ctx, msg_err.format(ctx.message.author, cprocessed, cmdfix, key))
            elif isinstance(exp.original, asyncio.TimeoutError):
                await self.csend(ctx, tim_err.format(ctx.message.author, cprocessed, cmdfix))
            elif ctx.command.name == 'eval':
                await self.csend(ctx, ast_err.format(ctx.message.author, cprocessed, cmdfix))
            else:
                await self.csend(ctx, '⚠ Error in `%s`!\n```' % (cmdfix + cprocessed) + bc_key + '```')
        elif type(exp) in (commands.MissingRequiredArgument, commands.TooManyArguments, commands.BadArgument):
            if ctx.invoked_subcommand is None:
                tgt_cmd = self.bot.commands[cprocessed]
            else:
                tgt_cmd = ctx.invoked_subcommand
            try:
                r_usage = bdel(bdel(bdel(tgt_cmd.help.split('\n')[-1], 'Usage: '),
                                         tgt_cmd.name), cprocessed)
            except AttributeError:
                r_usage = ''
            await self.csend(ctx, arg_err.format(ctx.message.author, cprocessed, cmdfix, cmdfix +
                             cprocessed + r_usage, arg_err_map[type(exp)]))
        else:
            await self.csend(ctx, '⚠ Error in `%s`!\n```' % (cmdfix + cprocessed) + bc_key + '```')
Exemple #6
0
 async def cmd_eval(self, ctx, *, code: str):
     """Evaluate some code, or a math expression.
     Usage: eval [code/expression]"""
     or_check_perms(ctx, ('bot_admin',))
     code = bdel(bdel(code, '```python').strip('`'), '```py')
     for key in eval_blocked:
         if re.search(key, code):
             await self.bot.say(ctx.message.author.mention + ' **Blocked keyword found!**')
             return False
     try:
         sio = StringIO()
         with async_timeout.timeout(3):
             with contextlib.redirect_stdout(sio):
                 m_result = await self.math_task(code)
         v = sio.getvalue()
         if v:
             m_result = v + str(m_result)
     except (asyncio.TimeoutError, RuntimeError) as exp:
         resp = '{0.author.mention} **It took too long to evaluate your expression!**'.format(ctx.message)
         if isinstance(exp, RuntimeError):
             if str(exp).startswith('Execution exceeded time limit, max runtime is '):
                 await self.bot.say(resp)
                 return
             else:
                 raise ValueError('ASTEval Error of type TimeoutError')
         else:
             await self.bot.say(resp)
         return
     _result = ''
     if self.bot.asteval.error:
         err_type = self.bot.asteval.error[0].get_error()[0]
         if err_type == 'MemoryError':
             await self.bot.reset_asteval(reason='due to MemoryError')
             await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
             return
         elif err_type in ['NameError', 'UnboundLocalError']:
             await self.bot.say(ctx.message.author.mention + ' **You tried to use a variable that didn\'t exist!**')
             return
         else:
             raise ValueError('ASTEval Error of type ' + err_type)
     else:
         try:
             _result = str(m_result)
         except MemoryError:
             await self.bot.reset_asteval(reason='due to MemoryError')
             await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
             return
     try:
         if m_result is None:
             _result = '✅'
         else:
             if not ctx.invoked_with.startswith('r'):
                 _result = '```py\n' + _result + '```'
     except MemoryError:
         await self.bot.reset_asteval(reason='due to MemoryError')
         await self.bot.say(ctx.message.author.mention + ' **Please re-run your `eval` command!**')
         return
     try:
         byte_size = await self.loop.run_in_executor(None, asizeof, self.bot.asteval.symtable)
         if byte_size > 50_000_000: # 110 MiB 115_343_360, 107 MiB 112_197_632, 107 MB 107_000_000
             await self.bot.reset_asteval(reason='due to memory usage > 50M', note=f'was using {byte_size / 1048576} MiB')
     except MemoryError:
         await self.bot.reset_asteval(reason='due to MemoryError during asizeof')
     else:
         del byte_size
     await self.bot.say(_result)