async def sql(self, ctx, *, query: CBStripConverter): """Run SQL statements""" is_multistatement = query.count(";") > 1 if is_multistatement: strategy = self.bot.pool.execute else: strategy = self.bot.pool.fetch start = time.perf_counter() try: results = await strategy(query) except asyncpg.PostgresError as error: await ctx.send( ctx.codeblock(content=tabulate([[str(error)]], headers=["error"]), lang="sql")) return 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 ] r = [] for item in [list(res.values()) for res in results]: 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 = [ str(ctx.codeblock(content=page)) for page in group(table, 1500) ] await ctx.paginate( pages, 1, delete_on_button=True, clear_reactions_after=True, timeout=300, template=discord.Embed().set_author( name=f'Returned {rows} {pluralize("row", rows)} in {dt:.2f}ms' ), )
class Dev(commands.Cog): """Commands made to assist with bot development""" def __init__(self, bot): self.bot = bot self.scope = {} self._last_result = None async def cog_check(self, ctx): return await self.bot.is_owner(ctx.author) @commands.command(aliases=["sh"]) async def shell(self, ctx, *, args: CBStripConverter): """Invokes the system shell, attempting to run the inputted command""" hl_lang = "sh" if match := file_ext_re.search(args): hl_lang = match.groupdict().get("extension", "sh") if "git diff" in args: hl_lang = "diff" async with ctx.loading(tick=False): shellout = await do_shell(args) output = ( clean_bytes(shellout.stdout) + "\n" + textwrap.indent(clean_bytes(shellout.stderr), "[stderr] ")) pages = group(output, 1500) pages = [ str(ctx.codeblock(content=page, lang=hl_lang)) + f"\n`Return code {shellout.returncode}`" for page in pages ] await ctx.paginate(pages, 1, delete_on_button=True, clear_reactions_after=True, timeout=1800)
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.paginate( group(output, 750) or ["No result"], 1, delete_on_button=True, clear_reactions_after=True, )
async def post_callback(ctx, post): embeds = [submission_to_embed(post)] for item in group(post.original_json[1]["data"]["children"], 5): embed = discord.Embed(title="Browsing top-level comments") for comment in item: embed.add_field( name=f"{reddit_emojis['upvote']} {comment['data'].get('ups')} | " f"u/{comment['data'].get('author')}", value= f"[🔗](https://reddit.com{comment['data'].get('permalink')})" f"{textwrap.shorten(comment['data'].get('body', ''), width=125)}", inline=False, ) embeds.append(embed) source = PagedEmbedMenu(embeds) menu = CSMenu(source, delete_message_after=True) await menu.start(ctx)
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, } clear_intersection(globals(), self.scope) env.update(**globals(), **self.scope) stdout = io.StringIO() to_return = None final_results = [] async with ctx.loading(): try: async for res in NeoEval(code=body, context=env, scope=self.scope): if res is None: continue self._last_result = res if not isinstance(res, str): res = repr(res) final_results.append(res) except Exception as e: to_return = format_exception(e) else: value = stdout.getvalue() or "" to_return = value + "\n".join(final_results) if to_return: pages = group(to_return, 1500) pages = [ str(ctx.codeblock(content=page, lang="py")) for page in pages ] await ctx.paginate( pages, 1, delete_on_button=True, clear_reactions_after=True, timeout=1800, )