Exemple #1
0
 def format_exception(self):
     fmtd_exc = ''.join(
         traceback.format_exception(type(self.error), self.error,
                                    self.error.__traceback__))
     formatted = ''.join(re.sub(r'File ".+",', 'File "<eval>"', fmtd_exc))
     pages = group(formatted, 1500)
     return [self.ctx.codeblock(page, 'py') for page in pages]
Exemple #2
0
 async def _ocr_command(self, ctx, *, image_url: str = None):
     """Run an image through Optical Character Recognition (OCR) and return any detected text"""
     if image_url is None and not ctx.message.attachments:
         raise commands.MissingRequiredArgument(
             Parameter(name='image', kind=Parameter.KEYWORD_ONLY))
     image = image_url or ctx.message.attachments[0].url
     async with timeout(30), ctx.loading(tick=False), self.bot.session.get(
             'https://api.tsu.sh/google/ocr', params={'q': image}) as resp:
         output = (await resp.json()).get('text', 'No result')
     await ctx.quick_menu(group(output, 1000), 1, delete_message_after=True)
Exemple #3
0
    async def sql(self, ctx, *, query: CBStripConverter):
        """Run SQL statements"""
        is_multistatement = query.count(';') > 1
        if is_multistatement:
            strategy = self.bot.conn.execute
        else:
            strategy = self.bot.conn.fetch

        start = time.perf_counter()
        results = await strategy(query)
        dt = (time.perf_counter() - start) * 1000.0

        rows = len(results)
        if is_multistatement or rows == 0:
            return await ctx.send(f'`{dt:.2f}ms: {results}`')
        rkeys = [*results[0].keys()]
        headers = [
            textwrap.shorten(col, width=40 // len(rkeys), placeholder='')
            for col in rkeys
        ]
        r2 = [list(r.values()) for r in results]
        r = []
        for item in r2:
            for i in item:
                r.append(
                    textwrap.shorten(str(i),
                                     width=40 // len(rkeys),
                                     placeholder=''))
        r = group(r, len(rkeys))
        table = tabulate(r, headers=headers, tablefmt='pretty')
        pages = [ctx.codeblock(page) for page in group(table, 1500)]
        await ctx.quick_menu(
            pages,
            1,
            delete_message_after=True,
            timeout=300,
            template=discord.Embed(color=discord.Color.main).set_author(
                name=f'Returned {rows} {pluralize("row", rows)} in {dt:.2f}ms')
        )
Exemple #4
0
 async def _dev_scope(self, ctx, toggle: BoolConverter = None):
     if toggle is None:
         pages = group(str(self.scope), 1500)
         pages = [ctx.codeblock(page, 'py') for page in pages]
         await ctx.quick_menu(pages,
                              1,
                              template=discord.Embed(
                                  title=f'Retain: {self.retain}',
                                  color=discord.Color.main),
                              delete_message_after=True,
                              timeout=300)
         return
     async with ctx.loading():
         self.retain = toggle
Exemple #5
0
 async def shell(self, ctx, *, args: CBStripConverter):
     """Invokes the system shell, attempting to run the inputted command"""
     hl_lang = 'sh'
     if 'cat' in args:
         hl_lang = return_lang_hl(args)
     if 'git diff' in args:
         hl_lang = 'diff'
     async with ctx.loading(tick=False):
         stdout, stderr = await do_shell(args)
         output = clean_bytes(stdout) + '\n' + textwrap.indent(
             clean_bytes(stderr), '[stderr] ')
         pages = group(output, 1500)
         pages = [ctx.codeblock(page, hl_lang) for page in pages]
     await ctx.quick_menu(pages, 1, delete_message_after=True, timeout=1800)
Exemple #6
0
 async def eval_(self, ctx, *, body: CBStripConverter):
     """Runs code that you input to the command"""
     env = {
         'bot': self.bot,
         'ctx': ctx,
         'channel': ctx.channel,
         'author': ctx.author,
         'guild': ctx.guild,
         'message': ctx.message,
         '_': self._last_result
     }
     env.update(globals())
     if self.retain:
         env.update(self.scope)
     stdout = io.StringIO()
     to_return = None
     to_compile = f'async def func(scope, should_retain=True):' \
                  f'\n  try:' \
                  f'\n{textwrap.indent(body, "    ")}' \
                  f'\n  finally:' \
                  f'\n    if not should_retain:' \
                  f'\n      return' \
                  f'\n    scope.update(locals())'
     async with ctx.loading(exc_ignore=HandleTb):
         try:
             import_expression.exec(to_compile, env)
         except Exception as e:
             raise HandleTb(ctx, e)
         evaluated_func = env['func']
         try:
             with redirect_stdout(stdout):
                 result = await evaluated_func(self.scope,
                                               self.retain) or ''
         except Exception as e:
             raise HandleTb(ctx, e)
         else:
             value = stdout.getvalue() or ''
             self._last_result = result
             to_return = f'{value}{result}'
     if to_return:
         pages = group(to_return, 1500)
         pages = [ctx.codeblock(page, 'py') for page in pages]
         await ctx.quick_menu(pages,
                              1,
                              delete_message_after=True,
                              timeout=1800)