async def sql(self, ctx, *, query: str): query = formatting.cleanup_code(query) is_multistatement = query.count(';') > 1 if is_multistatement: strategy = self.bot.pool.execute else: strategy = self.bot.pool.fetch try: start = time.perf_counter() results = await strategy(query) dt = (time.perf_counter() - start) * 1000.0 except Exception: return await ctx.send( formatting.codeblock(traceback.format_exc(), lang='py')) rows = len(results) if is_multistatement or rows == 0: return await ctx.send( formatting.codeblock(f'{dt:.2f}ms: {results}')) headers = list(results[0].keys()) table = formatting.TabularData() table.set_columns(headers) table.add_rows(list(r.values()) for r in results) render = table.render() fmt = f'{formatting.codeblock(render)}\n*Returned {formatting.pluralise(row=rows)} in {dt:.2f}ms*' if len(fmt) > 2000: fp = io.BytesIO(fmt.encode('utf-8')) await ctx.send('Too many results...', file=discord.File(fp, 'results.txt')) else: await ctx.send(fmt)
async def run(ctx: Context, args: Arguments) -> CommandResult: receive_time = time() msg = await ctx.send("Pinging...") request_complete_time = time() receive_diff = ( receive_time - (ctx.message.edited_at or ctx.message.created_at).timestamp() ) send_diff = request_complete_time - receive_time total_diff = ( msg.created_at.timestamp() - (ctx.message.edited_at or ctx.message.created_at).timestamp() ) return await msg.edit( content=( codeblock( f"Receive diff: {round(receive_diff / 1000)}ms\n" f"Message send: {round(send_diff * 1000)}ms\n" f"Total diff: {round(total_diff * 1000)}ms\n" f"WS latency: {round(ctx.bot.latency * 1000)}ms\n" ) ) )
async def run(ctx: Context, args: Arguments) -> CommandResult: if len(args) == 1: # TODO: syntax hints help_text = codeblock(await args[0].get_help(ctx)) return help_text commands = list( ctx.bot._handler.get_all_commands( with_hidden=ctx.author.id in ctx.bot.config["owners"])) commands.sort(key=lambda c: c.name) lines = [f"{c.name:<12}: {c.short_help}" for c in commands] pages = [ lines[i:i + LINES_PER_PAGE] for i in range(0, len(lines), LINES_PER_PAGE) ] p = RawPagePaginator(len(pages)) @p.on_page_switch async def f(current_page: int, next_page: int) -> PageType: nl = "\n" return (f"Список **{len(lines)}** доступных команд:" f"{codeblock(nl.join(pages[next_page]))}" f"Страница **{next_page + 1}** из **{p.size}**") return await p.run(ctx)
async def run(ctx: Context, args: Arguments) -> CommandResult: try: result = await ctx.bot.pg.fetch(" ".join(args)) except Exception as e: return f"Произошла ошибка: {codeblock(str(e))}" if len(result) > 0: table = TabularData() table.set_columns(list(result[0].keys())) table.add_rows(list(r.values() for r in result)) result = table.render() if len(result) > 2000: ii = 0 lines = [] for i in range(0, len(result), 1500): lines.append(result[ii:i]) ii = i p = RawPagePaginator(len(lines)) @p.on_page_switch async def f(current_page: int, next_page: int) -> PageType: nl = "" return (f"{codeblock(nl.join(lines[next_page]))}" f"Страница **{next_page + 1}** из **{p.size}**") return await p.run(ctx) return codeblock(result)
async def run(self, ctx: Context, args: Arguments) -> CommandResult: items = [i for i in Item.all_instances()] items.sort(key=lambda x: x.id) return codeblock( "\n".join(sorted(f"{item.id:>3} {item.name}" for item in items)) )
def on_message(msg, server): slack = Slack(msg, server) match = re.findall('^!help( .*)?$', msg['text']) if not match: return command = match[0].strip().replace('.', '') all_help_docs = [] for mod_name in server.hooks["extendedhelp"]: doc_list = json.loads(server.hooks["extendedhelp"][mod_name]) all_help_docs.extend(doc_list) # specific command if command: doc = [ item for item in all_help_docs if command.lower() == item["name"].lower() ][0] help_str = 'To the rescue!\n' output = doc['name'] arglist = [] for arg in doc['args']: if arg.startswith('('): arglist.append('[<' + arg.replace('(', '').replace(')', '') + '>]') else: arglist.append('<' + arg + '>') output += (' ' + ' '.join(arglist) if arglist else '') + '\n\n' output += doc['long_description'] + '\n\n' output += 'Example usage(s):\n\t' + '\n\t'.join(doc['examples']) return at(slack.user_name, help_str + codeblock(output)) command_lists = {} for doc in all_help_docs: arglist = [] for arg in doc['args']: if arg.startswith('('): arglist.append('[<' + arg.replace('(', '').replace(')', '') + '>]') else: arglist.append('<' + arg + '>') help_str = monospace(doc['name'] + (' ' + ' '.join(arglist) if arglist else '')) help_str += ': ' + italics(doc['short_description']) if "category" not in doc: doc["category"] = "Unspecified" if doc["category"] not in command_lists: command_lists[doc["category"]] = [help_str] else: command_lists[doc["category"]].append(help_str) bot_reply = "Here is the full list of accepted commands. " bot_reply += "Use `.help <command_name>` for details on a specific command.\n>>>" for category in sorted(command_lists): bot_reply += bold(category) + "\n" bot_reply += "\n".join(sorted(command_lists[category])) + "\n" return at(slack.user_name, bot_reply)
async def eval(self, ctx, *, body: str): env = { 'bot': self.bot, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, '_': self._last_result } async with ctx.channel.typing(): env.update(globals()) body = formatting.cleanup_code(body) stdout = io.StringIO() to_compile = f'async def func():\n{textwrap.indent(body, " ")}' try: exec(to_compile, env) except Exception as e: return await ctx.send( formatting.codeblock(f'{e.__class__.__name__}: {e}', lang='py')) func = env['func'] try: with redirect_stdout(stdout): ret = await func() except Exception as e: value = stdout.getvalue() await ctx.send(formatting.codeblock(f'{value}{e}', lang='py')) else: value = stdout.getvalue() if ret is None: if value: await ctx.send(formatting.codeblock(value, lang='py')) else: self._last_result = ret await ctx.send( formatting.codeblock(f'{value}{ret}', lang='py'))
async def run(ctx: Context, args: Arguments) -> CommandResult: info = { "time": time(), "prefix": ctx.prefix, "alias": ctx.alias, "arguments": len(args), "author": ctx.author, "guild": ctx.guild, } return codeblock("\n".join(f"{k}: {v}" for k, v in info.items()))
def on_message(msg, server): slack = Slack(msg, server) match = re.findall('^!help( .*)?$', msg['text']) if not match: return command = match[0].strip().replace('.', '') all_help_docs = [] for mod_name in server.hooks["extendedhelp"]: doc_list = json.loads(server.hooks["extendedhelp"][mod_name]) all_help_docs.extend(doc_list) # specific command if command: doc = [item for item in all_help_docs if command.lower() == item["name"].lower()][0] help_str = 'To the rescue!\n' output = doc['name'] arglist = [] for arg in doc['args']: if arg.startswith('('): arglist.append('[<' + arg.replace('(', '').replace(')', '') + '>]') else: arglist.append('<' + arg + '>') output += (' ' + ' '.join(arglist) if arglist else '') + '\n\n' output += doc['long_description'] + '\n\n' output += 'Example usage(s):\n\t' + '\n\t'.join(doc['examples']) return at(slack.user_name, help_str + codeblock(output)) command_lists = {} for doc in all_help_docs: arglist = [] for arg in doc['args']: if arg.startswith('('): arglist.append('[<' + arg.replace('(', '').replace(')', '') + '>]') else: arglist.append('<' + arg + '>') help_str = monospace(doc['name'] + (' ' + ' '.join(arglist) if arglist else '')) help_str += ': ' + italics(doc['short_description']) if "category" not in doc: doc["category"] = "Unspecified" if doc["category"] not in command_lists: command_lists[doc["category"]] = [help_str] else: command_lists[doc["category"]].append(help_str) bot_reply = "Here is the full list of accepted commands. " bot_reply += "Use `.help <command_name>` for details on a specific command.\n>>>" for category in sorted(command_lists): bot_reply += bold(category) + "\n" bot_reply += "\n".join(sorted(command_lists[category])) + "\n" return at(slack.user_name, bot_reply)
async def on_error(self, event, *args, **kwargs): await self.wait_until_ready() if self.owner_id is None: app = await self.application_info() self.owner_id = app.owner.id embed = discord.Embed(title='Error', colour=discord.Colour.red()) embed.add_field(name='Event', value=event) description = traceback.format_exc() description = formatting.truncate(description, 2000) embed.description = formatting.codeblock(description, lang='py') embed.timestamp = datetime.datetime.utcnow() owner = await self.get_user_info(self.owner_id) await owner.send(embed=embed)
async def on_command_error(self, ctx, error): if isinstance(error, commands.CommandNotFound): return elif isinstance(error, commands.BadArgument): await ctx.send(error) elif isinstance(error, commands.NoPrivateMessage): await ctx.send(error) elif isinstance(error, commands.DisabledCommand): await ctx.send('This command is disabled and cannot be used.') elif isinstance(error, commands.CommandOnCooldown): await ctx.send(f'This command is on cooldown. Please retry in {error.retry_after:.0f}s.') elif isinstance(error, commands.MissingRequiredArgument): await ctx.send(f'Missing parameter: {error.param.name}.') elif isinstance(error, commands.MissingPermissions): await ctx.send(f'You are missing permissions: {", ".join(error.missing_perms)}.') elif isinstance(error, commands.BotMissingPermissions): await ctx.send(f'I am missing permissions: {", ".join(error.missing_perms)}.') elif isinstance(error, commands.CommandInvokeError): trace = ''.join(traceback.format_exception(type(error.original), error.original, error.original.__traceback__)) log.error(f'Error in command {ctx.command.qualified_name}:') log.error(trace) embed = discord.Embed(title='Command Error', colour=discord.Colour.red()) embed.add_field(name='Command', value=ctx.command.qualified_name) embed.add_field(name='User', value=str(ctx.author)) embed.add_field(name='Message', value=formatting.truncate(ctx.message.content, 512) if ctx.message.content != '' else 'None') description = formatting.codeblock(trace, lang='py') embed.description = formatting.truncate(description, 2000) embed.timestamp = datetime.datetime.utcnow() owner = await self.get_user_info(self.owner_id) await owner.send(embed=embed) try: await ctx.author.send(f'{ctx.author.mention}, that command just broke me 😮. An error report has been sent to {self.get_user(self.owner_id).name} and a fix will follow shortly 👍.') except discord.errors.Forbidden: pass
async def send_async_error(self, loop, context): await self.wait_until_ready() if self.owner_id is None: app = await self.application_info() self.owner_id = app.owner.id embed = discord.Embed(title='Async Error', colour=discord.Colour.red()) if 'message' in context: embed.add_field(name='Message', value=context['message']) error = context['exception'] description = ''.join(traceback.format_exception(type(error), error, error.__traceback__)) description = formatting.truncate(description, 2000) embed.description = formatting.codeblock(description, lang='py') embed.timestamp = datetime.datetime.utcnow() owner = await self.get_user_info(self.owner_id) await owner.send(embed=embed)
async def run(self, ctx: Context, args: Arguments) -> CommandResult: try: player = await Player.from_id(ctx.author.id, ctx.bot.pg) except UnknownPlayer: return "У вас нет персонажа" if player.inventory.size: inventory = "\n".join(str(i) for i in player.inventory) else: inventory = "Ваш инвентарь пуст" equipment_item_map = [(slot, getattr(player.equipment, slot)) for slot in player.equipment._slots] equipment = "\n".join(f"{slot:>10}: {item}" for (slot, item) in equipment_item_map) return codeblock( f"Экипировка:\n\n{equipment}\n\nИнвентарь:\n\n{inventory}")
async def run(ctx: Context, args: Arguments) -> CommandResult: player = await get_author_player(ctx) if player.inventory.size: counts: Dict[Item, int] = {} for item in player.inventory: counts[item] = counts.get(item, 0) + 1 inventory = "\n".join( f"{item}{' x ' + str(count) if count > 1 else ''}" for item, count in counts.items() ) else: inventory = "Ваш инвентарь пуст" equipment_item_map = [ (slot, getattr(player.equipment, slot)) for slot in player.equipment._slots ] equipment = "\n".join(f"{slot:>10}: {item}" for (slot, item) in equipment_item_map) return codeblock(f"Экипировка:\n\n{equipment}\n\nИнвентарь:\n\n{inventory}")