async def pendingbots(self, ctx, **flags): bots = await self.bot.pool_pg.fetch("SELECT * FROM pending_bots") menu = MenuBase( bot_pending_list( sorted(bots, key=lambda x: x["requested_at"], reverse=not flags.get("reverse", False)))) menu.cached_bots = self.cached_bots await menu.start(ctx)
async def recentbotadd(self, ctx, **flags): reverse = flags.pop("reverse", False) def predicate(m): return m.bot and m.joined_at.replace( tzinfo=None) > ctx.message.created_at.replace( tzinfo=None) - datetime.timedelta(days=1) members = {m.id: m for m in filter(predicate, ctx.guild.members)} if not members: member = max(filter(lambda x: x.bot, ctx.guild.members), key=lambda x: x.joined_at) time_add = humanize.precisedelta( member.joined_at.replace(tzinfo=None), minimum_unit="minutes") return await ctx.embed( title="Bots added today", description= "Looks like there are no bots added in the span of 24 hours.\n" f"The last time a bot was added was `{time_add}` for `{member}`" ) db_data = await self.bot.pool_pg.fetch( "SELECT * FROM confirmed_bots WHERE bot_id=ANY($1::BIGINT[])", list(members)) member_data = [ BotAdded.from_json(bot=members[data["bot_id"]], **data) for data in db_data ] member_data.sort(key=lambda x: x.joined_at, reverse=not reverse) menu = MenuBase(source=bot_added_list(member_data)) await menu.start(ctx)
async def botrank(self, ctx, bot: greedy_parser.UntilFlag[BotCommands] = None, **flags): reverse = flags.pop("reverse", False) bots = {x.id: x for x in ctx.guild.members if x.bot} query = "SELECT bot_id, COUNT(command) AS total_usage FROM commands_list " \ "WHERE guild_id=$1 AND bot_id=ANY($2::BIGINT[]) " \ "GROUP BY bot_id" record = await self.bot.pool_pg.fetch(query, ctx.guild.id, list(bots)) bot_data = [ BotCommands(bots[r["bot_id"]], 0, 0, r["total_usage"]) for r in record ] bot_data.sort(key=lambda x: x.total_usage, reverse=not reverse) if not bot: menu = MenuBase(source=all_bot_count(bot_data)) await menu.start(ctx) else: key = "(\u200b|\u200b)" idx = [*map(int, bot_data)].index(bot.bot.id) scope_bot = bot_data[idx:min(idx + len(bot_data[idx:]), idx + 10)] contents = [ "`{0}. {1} {2} {1.total_usage}`".format(i + idx + 1, b, key) for i, b in enumerate(scope_bot) ] await ctx.embed(title="Bot Command Rank", description="\n".join(realign(contents, key)))
async def allcommands(self, ctx, **flags): reverse = flags.get("reverse", False) query = "SELECT * FROM " \ "(SELECT command, COUNT(command) AS command_count FROM " \ "(SELECT DISTINCT bot_id, command FROM commands_list " \ "WHERE guild_id=$1 " \ "GROUP BY bot_id, command) AS _ " \ "GROUP BY command) AS _ " \ f"ORDER BY command_count {('DESC', '')[reverse]}" data = await self.bot.pool_pg.fetch(query, ctx.guild.id) @pages(per_page=6) async def each_commands_list(self, menu: MenuBase, entries): offset = menu.current_page * self.per_page embed = BaseEmbed(title=f"All Commands") key = "(\u200b|\u200b)" contents = [ "`{i}. {command}{k}{command_count}`".format(i=i, k=key, **b) for i, b in enumerate(entries, start=offset + 1) ] embed.description = "\n".join(realign(contents, key)) return embed menu = MenuBase(each_commands_list(data)) await menu.start(ctx)
def printing(*content, now=False, channel=ctx, reply=True, mention=False, **kwargs): async def sending(cont): nonlocal channel, reply, mention if c := channel is not ctx: channel = await commands.TextChannelConverter().convert( ctx, str(channel)) attr = ("send", "reply")[reply is not c] sent = getattr(channel, attr) text = textwrap.wrap(cont, 1000, replace_whitespace=False) ctx.channel_used = channel if channel is not ctx else ctx.channel if len(text) == 1: kwargs = {"content": cont} if attr == "reply": kwargs.update({"mention_author": mention}) await sent(**kwargs) else: menu = MenuBase( empty_page_format([*map("```{}```".format, text)])) await menu.start(ctx)
async def format_page(self, menu: MenuBase, entries): key = "(\u200b|\u200b)" offset = menu.current_page * self.per_page content = "`{no}. {b} {key} {b.count}`" contents = [content.format(no=i+1, b=b, key=key) for i, b in enumerate(entries, start=offset)] embed = BaseEmbed(title="Bot Command Rank", description="\n".join(realign(contents, key))) return menu.generate_page(embed, self._max_pages)
async def format_page(self, menu: MenuBase, entries): key = "(\u200b|\u200b)" offset = menu.current_page * self.per_page content = "`{no}. {prefix} {key} {b.count}`" if self.count_mode else "`{no}. {b} {key} {prefix}`" contents = [content.format(no=i+1, b=b, key=key, prefix=pprefix(menu.ctx.bot, b.prefix)) for i, b in enumerate(entries, start=offset)] embed = BaseEmbed(title="All Prefixes", description="\n".join(realign(contents, key))) return menu.generate_page(embed, self._max_pages)
async def format_page(self, menu: MenuBase, entries): offset = menu.current_page * self.per_page contents = ((f"{b.author}", f'**{b}** `{humanize.precisedelta(b.joined_at)}`') for i, b in enumerate(entries, start=offset)) embed = BaseEmbed(title="Bots added today") for n, v in contents: embed.add_field(name=n, value=v, inline=False) return menu.generate_page(embed, self._max_pages)
async def botcommands(self, ctx, bot: BotCommand): @pages(per_page=6) def each_page(self, menu, entries): number = menu.current_page * self.per_page + 1 list_commands = "\n".join(f"{x}. {c}" for x, c in enumerate(entries, start=number)) embed = BaseEmbed.default(ctx, title=f"{bot} Commands", description=list_commands) return embed.set_thumbnail(url=bot.bot.avatar_url) menu = MenuBase(each_page(bot.commands)) await menu.start(ctx)
async def allprefix(self, ctx, **flags): bots = await self.bot.pool_pg.fetch("SELECT * FROM bot_prefix") attr = "count" if (count_mode := flags.pop("count", False)) else "prefix" def mem(x): return ctx.guild.get_member(x) if count_mode: PrefixCount = collections.namedtuple("PrefixCount", "prefix count") count_prefixes = collections.Counter(map(lambda x: x["prefix"], bots)) data = [PrefixCount(*a) for a in count_prefixes.items()] else: data = [BotPrefix(mem(bot["bot_id"]), bot["prefix"]) for bot in bots if mem(bot["bot_id"])] data.sort(key=lambda x: getattr(x, attr), reverse=count_mode) menu = MenuBase(source=AllPrefixes(data, count_mode), delete_message_after=True) await menu.start(ctx)
async def botrank(self, ctx, bot: BotUsage = None): bots = {x.id: x for x in ctx.guild.members if x.bot} query = "SELECT * FROM bot_usage_count WHERE bot_id=ANY($1::BIGINT[])" record = await self.bot.pool_pg.fetch(query, list(bots)) bot_data = [BotUsage(bots[r["bot_id"]], r["count"]) for r in record] bot_data.sort(key=lambda x: x.count, reverse=True) if not bot: menu = MenuBase(source=AllBotCount(bot_data), delete_message_after=True) await menu.start(ctx) else: key = "(\u200b|\u200b)" idx = [*map(int, bot_data)].index(bot.bot.id) scope_bot = bot_data[idx:min(idx + len(bot_data[idx:]), idx + 10)] contents = ["`{0}. {1} {2} {1.count}`".format(i + idx + 1, b, key) for i, b in enumerate(scope_bot)] embed = BaseEmbed(title="Bot Command Rank", description="\n".join(realign(contents, key))) await ctx.maybe_reply(embed=embed)
async def recentbotadd(self, ctx): def predicate(m): return m.bot and m.joined_at > ctx.message.created_at - datetime.timedelta(days=1) members = {m.id: m for m in filter(predicate, ctx.guild.members)} if not members: member = max(filter(lambda x: x.bot, ctx.guild.members), key=lambda x: x.joined_at) time_add = humanize.precisedelta(member.joined_at, minimum_unit="minutes") await ctx.maybe_reply( embed=BaseEmbed.default( ctx, title="Bots added today", description="Looks like there are no bots added in the span of 24 hours.\n" f"The last time a bot was added was `{time_add}` for `{member}`")) return db_data = await self.bot.pool_pg.fetch("SELECT * FROM confirmed_bots WHERE bot_id=ANY($1::BIGINT[])", list(members)) member_data = [BotAdded.from_json(bot=members[data["bot_id"]], **data) for data in db_data] member_data.sort(key=lambda x: x.joined_at) menu = MenuBase(source=BotAddedList(member_data), delete_message_after=True) await menu.start(ctx)
async def allprefix(self, ctx, **flags): bots = await self.bot.pool_pg.fetch("SELECT * FROM bot_prefix_list") attr = "count" if (count_mode := flags.pop("count", False)) else "prefix" reverse = flags.pop("reverse", False) def mem(x): return ctx.guild.get_member(x) temp = {} for bot in filter(lambda b: mem(b["bot_id"]), bots): prefixes = temp.setdefault(bot["bot_id"], {bot["prefix"]: bot["usage"]}) prefixes.update({bot["prefix"]: bot["usage"]}) data = [BotPrefix(mem(b), v) for b, v in temp.items()] if count_mode: PrefixCount = collections.namedtuple("PrefixCount", "prefix count") aliases = itertools.chain.from_iterable(map(lambda x: x.aliases, data)) count_prefixes = collections.Counter([*map(lambda x: x.prefix, data), *aliases]) data = [PrefixCount(*a) for a in count_prefixes.items()] data.sort(key=lambda x: getattr(x, attr), reverse=count_mode is not reverse) menu = MenuBase(source=AllPrefixes(data, count_mode)) await menu.start(ctx)
async def botcommands(self, ctx, *, bot: BotCommands): owner_info = None if ctx.guild.id == DISCORD_PY: owner_info = await try_call(BotAdded.convert, ctx, str(int(bot))) @pages(per_page=6) def each_page(self, menu, entries): number = menu.current_page * self.per_page + 1 list_commands = "\n".join( f"{x}. {c}[`{bot.get_command(c)}`]" for x, c in enumerate(entries, start=number)) embed = BaseEmbed.default( ctx, title=f"{bot} Commands[`{bot.total_usage}`]", description=list_commands) if owner_info and owner_info.author: embed.set_author(icon_url=owner_info.author.avatar.url, name=f"Owner {owner_info.author}") return embed.set_thumbnail(url=bot.bot.avatar.url) menu = MenuBase(each_page(bot.commands)) await menu.start(ctx)
if (given := flags.pop("max_row")) - MR: await ctx.maybe_reply( f"Showing `{given}` rows was more than `1430` characters(`{was_size}`), showing `{MR}` rows instead.", delete_after=60) tabledata = [*more_itertools.chunked(table[3:], MR)] for few_row in tabledata: last_row = [] if few_row is tabledata[-1] else last_row datarows.append(table[:3] + few_row + last_row) to_display = ["\n".join(row) for row in datarows] else: to_display = textwrap.wrap(str(rows), 1000, replace_whitespace=False) menu = MenuBase(show_result(to_display)) await menu.start(ctx) def setup(bot): cog = Myself(bot) for name in ("load", "unload", "reload"): @commands.command(name=name, aliases=["c" + name, name + "s"], cls=GreedyParser) async def _cog_load(self, ctx, extension: Separator[ValidCog]): await self.cogs_handler(ctx, extension) cog.__cog_commands__ += (_cog_load, ) bot.add_cog(cog)
class Helpful(commands.Cog): def __init__(self, bot): self._default_help_command = bot.help_command bot.help_command = StellaBotHelp() bot.help_command.cog = self self.bot = bot @commands.command(aliases=["ping", "p"], help="Shows the bot latency from the discord websocket.") async def pping(self, ctx): await ctx.embed( title="PP", description=f"Your pp lasted `{self.bot.latency * 1000:.2f}ms`") @commands.command(aliases=["up"], help="Shows the bot uptime from when it was started.") async def uptime(self, ctx): c_uptime = datetime.datetime.utcnow() - self.bot.uptime await ctx.embed( title="Uptime", description=f"Current uptime: `{humanize.precisedelta(c_uptime)}`") @commands.command( aliases=["src", "sources"], brief="Shows the source code link in github.", help="Shows the source code in github given the cog/command name. " "Defaults to the stella_bot source code link if not given any argument. " "It accepts 2 types of content, the command name, or the Cog method name. " "Cog method must specify it's Cog name separate by a period and it's method.", cls=flg.SFlagCommand) @flg.add_flag( "--code", type=bool, action="store_true", default=False, help= "Shows the code block instead of the link. Accepts True or False, defaults to False if not stated." ) async def source(self, ctx, content=None, **flags): source_url = 'https://github.com/InterStella0/stella_bot' if not content: return await ctx.embed(title="here's the entire repo", description=source_url) src, module = None, None def command_check(command): nonlocal src, module if command == 'help': src = type(self.bot.help_command) module = src.__module__ else: obj = self.bot.get_command(command.replace('.', ' ')) if obj and obj.cog_name != "Jishaku": src = obj.callback.__code__ module = obj.callback.__module__ def cog_check(content): nonlocal src, module if "." not in content: return cog, _, method = content.partition(".") cog = self.bot.get_cog(cog) if method_func := getattr(cog, method, None): module = method_func.__module__ target = getattr(method_func, "callback", method_func) src = target.__code__ for func in (command_check, cog_check): if not src: func(content) if module is None: return await ctx.maybe_reply(f"Method {content} not found.") show_code = flags.pop("code", False) if show_code: param = { "text": inspect.getsource(src), "width": 1900, "replace_whitespace": False } list_codeblock = [ f"```py\n{cb}\n```" for cb in textwrap.wrap(**param) ] menu = MenuBase(empty_page_format(list_codeblock)) await menu.start(ctx) else: lines, firstlineno = inspect.getsourcelines(src) location = module.replace('.', '/') + '.py' url = f'<{source_url}/blob/master/{location}#L{firstlineno}-L{firstlineno + len(lines) - 1}>' await ctx.embed(title=f"Here's uh, {content}", description=f"[Click Here]({url})")
prefixes = temp.setdefault(bot["bot_id"], {bot["prefix"]: bot["usage"]}) prefixes.update({bot["prefix"]: bot["usage"]}) data = [BotPrefixes(mem(b), v) for b, v in temp.items()] if count_mode: PrefixCount = collections.namedtuple("PrefixCount", "prefix count") aliases = itertools.chain.from_iterable( map(lambda x: x.aliases, data)) count_prefixes = collections.Counter( [*map(lambda x: x.prefix, data), *aliases]) data = [PrefixCount(*a) for a in count_prefixes.items()] data.sort(key=lambda x: getattr(x, attr), reverse=count_mode is not reverse) menu = MenuBase(source=AllPrefixes(data, count_mode)) await menu.start(ctx) @commands.command( aliases=["bot_use", "bu", "botusage", "botuses"], brief="Show's how many command calls for a bot.", help= "Show's how many command calls for a given bot. This works by counting how many times " "a message is considered a command for that bot where that bot has responded in less than " "2 seconds.") async def botuse(self, ctx, *, bot: BotCommands): await ctx.embed( title=f"{bot}'s Usage", description=plural( f"`{bot.total_usage}` command(s) has been called for **{bot}**.", bot.total_usage))