async def unmarkdown(self, ctx, *, message: discord.Message): """Get the raw version of a message. if the message ID isnt in the current channel, provide the message link or the channel_id-message_id.""" p = commands.Paginator(prefix='```md') if len(message.embeds) > 0: p.add_line( utils.escape_markdown(message.embeds[0].description, ignore_links=False)) p.add_line(utils.escape_markdown(message.content, ignore_links=False)) for pa in p.pages: await ctx.send(pa)
async def snippets_command(self, ctx: Kaantext) -> None: """ vs code python snippets """ msg = self.resource_texts['snippets'] p = commands.Paginator(prefix='```json', suffix='```') for line in msg.split('\n'): p.add_line(line) for page in p.pages: await ctx.send(page)
def create_summary(self, user: discord.User, commits): paginator = commands.Paginator(prefix="", suffix="") for line in self.summary_header: paginator.add_line(line.format(user=user.name, total_commits=len(commits))) for commit_id, commit in enumerate(commits): paginator.add_line( self.summary_format.format(commit_id=commit_id + 1, commit_message=commit["message"].split("\n")[0], commit_hash=commit["hash"])) return paginator.pages
async def on_ready(): print("Working boi!") global data global userd global lastping global gamestate global starttime global logz global active global lobby global peochannel global annchannel global guildd lobby = bot.get_channel(822501206848438272) peochannel = bot.get_channel(822512693851193375) annchannel = bot.get_channel(823843532912459786) guildd = bot.get_guild(822497162448732192) #await lobby.send("Who's up for a game?! :smiley:") await annchannel.send("The bot is online!") await bot.change_presence( activity=discord.Game(name="Deception: Murder in Hong Kong", type=1)) try: my_collection = db.main my_collection_t = db.user data = my_collection.find_one() userd = my_collection_t.find_one() gamestate = data['gamestate'] lastping = None logz = commands.Paginator(prefix="", suffix="") except: print("Could not load the data") data = {} data['signedup'] = {} data['players'] = {} data['gamestate'] = 0 gamestate = data['gamestate'] lastping = None data['job'] = {} #stuff userd = {} userd['users'] = {} await annchannel.send("The notif list has been erased!!!") if len(data['signedup']) > 0 and gamestate == 0: starttime = datetime.datetime.now() timeoutloop.start() if data['gamestate'] > 0: msg = await lobby.send( "Terribly sorry for the inconvenience, but it seems like the bot went offline during the game. As a result, the game probably malfunctioned and so I am going to automatically force end it. Contact the admins to do the rest. Again, sorry for the inconvenience." ) ctx = await bot.get_context(msg) await forceend(ctx) dump()
async def _send_command_list(self, full_mapping: set[Command]): """Help function which sends the command list. Factored out for DRYer code.""" categories: dict[str, list[str]] = {} # List of categorized commands. filtered_mapping = { f"`{com.qualified_name}`": com for com in await self.filter_commands(full_mapping) } non_passing = list( set(full_mapping).difference(set(filtered_mapping.values()))) new_message = copy.copy(self.context.message) new_message.guild = None new_ctx = await self.context.bot.get_context(new_message) dm_only = { f"`{com.qualified_name}`ยน": com for com in non_passing if await can_run(com, new_ctx) } filtered_mapping.update(dm_only) if not filtered_mapping: await self.get_destination().send( "No help information was found.") return for com_text, com in filtered_mapping.items(): if com.qualified_name in self.context.bot.help.keys(): command_help = self.context.bot.help[ com.qualified_name] # Get command help info. category = command_help.category.lower( ) if command_help.category else "no category" if category not in categories: # Add category if it wasn't encountered before. categories[category] = [] categories[category].append( com_text) # Add command to category. paginator = commands.Paginator(prefix="", suffix="", linesep="") paginator.add_line( f"__**Help Info {self.context.message.author.mention}:**__\n\n" ) for category in sorted(categories.keys()): paginator.add_line(f"**{category.title()}**\n") category_commands = [ f"{com}, " for com in sorted(categories[category]) ] category_commands[ -1] = f"{category_commands[-1][:-2]}\n\n" # Replace ', ' with '\n\n' on last command for com in category_commands: paginator.add_line(self.remove_mentions(com)) end = "1 = In DMs only.\n" if any("ยน" in elem for cat in categories.values() for elem in cat) else "" end += f"Use `{self.context.bot.get_bot_prefix()}help <COMMAND>` for more info on individual commands." paginator.add_line(end) for page in paginator.pages: await self.get_destination().send(page)
def paginate_exception(e): if hasattr(e, "original"): exc = e.original else: exc = e tblines = traceback.format_exception(type(exc), exc, exc.__traceback__) paginator = commands.Paginator( prefix=f"**`ERROR:`** {type(e).__name__} - {e}\n```", suffix="```" ) for line in tblines: paginator.add_line(line) return paginator.pages
async def session_start(self, ctx: commands.context): """ Start a new coc session """ if self.session_message != 0: return await ctx.send( "There is an active session right now.\n" "Join by reacting to the pinned message or using `t.coc session join`. Have fun!" ) pager = commands.Paginator( prefix=f"**Hey, {ctx.author.mention} is starting a coc session.\n" f"Use `t.coc session join` or react to this message to join**", suffix="") for member in self.role.members: if member != ctx.author: if member.status != discord.Status.offline: pager.add_line(member.mention + ", ") if not len(pager.pages): return await ctx.send( f"{ctx.author.mention}, Nobody is online to play with <:pepesad:733816214010331197>" ) self.session = True self.last_clash = int(time.time()) self.session_users.append(ctx.author.id) msg = await ctx.send(pager.pages[0]) self.session_message = msg.id await msg.add_reaction("๐๏ธ") try: await msg.pin() except: await ctx.send("Failed to pin message") while self.session_message != 0: await asyncio.sleep(10) if self.last_clash + 1800 < int( time.time()) and self.session_message != 0: await ctx.send( "Clash session has been closed due to inactivity") try: await msg.unpin() except: await ctx.send("Failed to unpin message") self.last_clash = 0 self.session_users = [] self.session_message = 0 self.session = False break
async def on_command_error(self, ctx, exception): channel = await self.fetch_channel(int(config["Config"]["Channel ID"])) await channel.send( f"<@&{self.role}> an unhandled exception has occurred") # by saying this we imply that some errors *are* handled gracefully exc = getattr(exception, 'original', exception) msg = "".join(format_exception(type(exc), exc, exc.__traceback__)) error_paginator = commands.Paginator() for chunk in [msg[i:i + 1800] for i in range(0, len(msg), 1800)]: error_paginator.add_line(chunk) for page in error_paginator.pages: await channel.send(page)
async def list_cogs(ctx): '''Lists all cogs and their status of loading.''' cog_list = commands.Paginator(prefix='', suffix='') cog_list.add_line('**โ Succesfully loaded:**') for cog in bot.loaded_cogs: cog_list.add_line('- ' + cog) cog_list.add_line('**โ Not loaded:**') for cog in bot.unloaded_cogs: cog_list.add_line('- ' + cog) for page in cog_list.pages: await ctx.send(page)
def codeblock(contents, syntax="py"): """Returns a list of codeblock text for the given content. Content is broken into items with a character limitation to avoid going above single-message limits. """ paginator = commands.Paginator( prefix='```{}'.format(syntax), max_size=2000) for line in contents.split('\n'): for wrapline in textwrap.wrap(line, width=1990): paginator.add_line(wrapline.rstrip().replace('`', '\u200b`')) return paginator.pages
async def cmdstats(self, ctx): await ctx.message.delete() p = commands.Paginator() counter = self.bot.commands_triggered width = len(max(counter, key=len)) total = sum(counter.values()) fmt = '{0:<{width}}: {1}' p.add_line(fmt.format('Total', total, width=width)) for key, count in counter.most_common(): p.add_line(fmt.format(key, count, width=width)) for page in p.pages: await ctx.send(page, delete_after=20)
async def all(self, ctx): """ Gives the list of all the languages supported by the translator """ async with ctx.channel.typing(): all_languages = googletrans.LANGUAGES pager = commands.Paginator() for key, value in all_languages.items(): pager.add_line(f"{key} - {value.title()}") for pages in pager.pages: await ctx.send(pages)
async def inv(self, ctx, guild: int): """Get all the invites of the server.""" try: guildid = self.bot.get_guild(guild) guildinvs = await guildid.invites() pager = commands.Paginator() for Invite in guildinvs: pager.add_line(Invite.url) for page in pager.pages: await ctx.send(page) except discord.Forbidden: await ctx.send(f"{emotes.warning} Was unable to fetch invites.")
async def paginate(log, destination): """Paginates and sends to a channel""" paginator = commands.Paginator() while log: try: paginator.add_line(log) log = '' except: paginator.add_line(log[:1992]) log = log[1992:] for page in paginator.pages: await destination.send(page)
def _list(self, ctx): """ Displays a list of editable settings. """ paginator = commands.Paginator() for dirpath, dirnames, filenames in self.data_man.walk_json(): for filename in filenames: no_ext = filename.split('.')[0] # remove filename extension paginator.add_line(line='-- \'{0}\''.format(no_ext)) pages = paginator.pages for p in pages: yield from self.bot.say(p)
def __init__(self, **options): options['verify_checks'] = False super().__init__(**options) self.paginator = commands.Paginator(max_size=1985) self.commands_heading = "Commands" self.aliases_heading = "Aliases:" self.no_category = "No Category" self.command_attrs = { 'description': "Provides help for various commands.", 'cooldown': commands.Cooldown(3, 10, commands.BucketType.channel), 'name': 'help' }
async def servers(self, ctx): """Lists servers.""" paginator = commands.Paginator(prefix="```md") for number, guild in enumerate(ctx.bot.guilds, start=1): dot = '\u200B.' backtick = '\u200B`' paginator.add_line( discord.utils.escape_markdown( f'{number}) {guild.name.replace(".", dot).replace("`", backtick)}\n' )) for page in paginator.pages: await ctx.send(page)
async def user_show(self, ctx): """DMs the blacklist. noirscape & Staff & Helpers only.""" paginator = commands.Paginator(prefix='', suffix='') paginator.add_line('___Blacklisted users___') for blacklisted_user in self.blacklisted_users: paginator.add_line('{} (ID: {})'.format( str(await self.bot.get_user_info(blacklisted_user)), blacklisted_user)) for page in paginator.pages: await ctx.author.send(page)
async def servers(self, ctx): """list servers""" if ctx.invoked_subcommand is None: pages = commands.Paginator() for num, guild in enumerate(self.bot.guilds, start=1): pages.add_line(f"{num}. {guild.name} ({guild.id})") pages.add_line(empty=True) for page in pages.pages: await ctx.send(page) await asyncio.sleep(1) await ctx.send( f"Guilds: {len(self.bot.guilds)}\nPages: {len(pages.pages)}")
async def servers(self, ctx): """Lists servers.""" paginator = PaginatorEmbedInterface( self.bot, commands.Paginator(prefix="```md", max_size=500)) for number, guild in enumerate(ctx.bot.guilds, start=1): dot = '\u200B.' backtick = '\u200B`' await paginator.add_line( discord.utils.escape_markdown( f'{number}. {guild.name.replace(".", dot).replace("`", backtick)}\n' )) await paginator.send_to(ctx.channel)
async def send_traceback(ctx: commands.Context, verbosity: int, *exception_info): type_, value, trace = exception_info content = ''.join(traceback.format_exception(type_, value, trace, verbosity)) content = content.replace('``', '`\u200b`').replace(ctx.bot.http.token, '[token omitted]') paginator = commands.Paginator(prefix='```py') for line in content.split('\n'): paginator.add_line(line) menu = Menu(paginator.pages) await menu.start(ctx)
async def pagtest(self, ctx): p = commands.Paginator() for i in range(100): try: p.add_line(line=str(i * i) + "ggggggggggggggggggggggggggggggggggggggggggggg") except: p.close_page() p.add_line(line=str(i * i) + "gdsfdsfdasfdsfdsffdsfsdsdfdfdsfsdfsdsdfsfsfdfs") print(p.pages) await ctx.send(p.pages[0])
async def _eval(self, ctx, *, body: str): """Evaluates a code""" env = { 'bot': ctx.bot, 'ctx': ctx, 'channel': ctx.channel, 'author': ctx.author, 'guild': ctx.guild, 'message': ctx.message, 'guild_dict': ctx.bot.guild_dict } def cleanup_code(content): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n') env.update(globals()) body = 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(f'```py\n{e.__class__.__name__}: {e}\n```') func = env['func'] try: with redirect_stdout(stdout): ret = await func() except Exception as e: value = stdout.getvalue() await ctx.send(f'```py\n{value}{traceback.format_exc()}\n```') else: value = stdout.getvalue() try: await ctx.message.add_reaction('\u2705') except: pass if ret is None: if value: paginator = commands.Paginator(prefix='```py') for line in textwrap.wrap(value, 80): paginator.add_line(line.rstrip().replace( '`', '\u200b`')) for p in paginator.pages: await ctx.send(p) else: ctx.bot._last_result = ret await ctx.send(f'```py\n{value}{ret}\n```')
async def _help(self, ctx, *, command: str = None): """Get help on a specified cog or command. Don't put any arguments to get a list of available commands.""" pref = '```\n' postf = f'Get info on a command group, category or just a command with @{self.bot.user.name}#{self.bot.user.discriminator} help <Category>/<Command>/<Command group> or *help <Category>/<Command>/<Command group>' result = '' postfix = '\n```' paginator = commands.Paginator() if not command: li = [cog for cog in self.bot.cogs] for smth in li: if smth != 'Help': s = list(self.bot.cogs[smth].get_commands()) if s: paginator.add_line(f"{s[0].cog_name}:") for c in s: if not c.hidden: paginator.add_line( f' {c.name} - {c.short_doc}') paginator.add_line(postf) for page in paginator.pages: await ctx.send(page) else: if command not in self.bot.all_commands: if command not in self.bot.cogs: cmd = self.bot.get_command( command.replace('*', '').replace(self.bot.user.mention, '')) if cmd: paginator.add_line( f"{ctx.prefix.replace(self.bot.user.mention, f'@{self.bot.user.name}#{self.bot.user.discriminator} ')}{cmd.signature}\n\n {cmd.help}" ) for page in paginator.pages: await ctx.send(page) else: result = 'That command/category/command group does not exist!' await ctx.send(result) else: the_cog = list(command.get_commands()) paginator.add_line(f"{the_cog[0].cog_name}:") for cmd in the_cog: if not cmd.hidden: paginator.add_line(f' {cmd.name} - {cmd.help}') paginator.add_line(postf) for page in paginator.pages: await ctx.send(page) else: cmd = self.bot.get_command( command.replace('*', '').replace(self.bot.user.mention, '')) result += f"{ctx.prefix.replace(self.bot.user.mention, f'@{self.bot.user.name}#{self.bot.user.discriminator} ')}{cmd.signature}\n\nCog: {cmd.cog_name}\n\n {cmd.help}" await ctx.send(f"{pref}{result}{postfix}")
async def cache(self, ctx): """ tell you how many messages the bot have cached if you don't know what is cache then this is not the right command for you """ paginator = commands.Paginator(max_size=1000) lines = list(self.bot.cached_messages) lines.append( f"Total amount of messages cached {len(self.bot.cached_messages)}") for i in lines: i = str(i) paginator.add_line(i) interface = PaginatorInterface(ctx.bot, paginator, owner=ctx.author) await interface.send_to(ctx)
def __call__(self, parser, namespace, values, option_string=None): paginator = commands.Paginator() help_txt = parser.format_help() for line in help_txt.split("\n"): try: paginator.add_line(line) except RuntimeError: for subline in chunkstring(line, paginator.max_size - 10): paginator.add_line(subline) for page in paginator.pages: parser.loop.create_task(parser.ctx.send(page)) raise commands.BadArgument # To exit silently
async def long(self, ctx): p = commands.Paginator(prefix='```css') with open('config/commands.json', 'r') as com: cmds = json.load(com) p.add_line('[List of Custom Commands]') width = len(max(cmds, key=len)) for cmd in sorted(cmds): p.add_line('{0:<{width}}| {1}'.format(cmd, cmds.get(cmd), width=width)) for page in p.pages: await ctx.send(page, delete_after=20) await ctx.message.delete()
async def roles(self, ctx): roles = database.roles.get_all_guild_roles(ctx.guild.id) pages = commands.Paginator() pages.add_line(f'{ctx.guild.name} has the following roles:\n') pages.add_line('/role <role name> | Role assigned') pages.add_line('---------------------|--------------------------') for role in ctx.guild.role_hierarchy: for row in roles: if role.id == row.role_id: pages.add_line(f'{row.alias.ljust(20)} | {role.name}') for page in pages.pages: await ctx.author.send(page) await ctx.message.add_reaction('โ')
def __init__(self, **options): self.sort_commands = options.pop('sort_commands', True) self.commands_heading = options.pop('commands_heading', "Commands") self.dm_help = options.pop('dm_help', False) self.dm_help_threshold = options.pop('dm_help_threshold', 1000) self.aliases_heading = options.pop('aliases_heading', "Aliases:") self.no_category = options.pop('no_category', 'No Category') self.paginator = options.pop('paginator', None) if self.paginator is None: self.paginator = cmd.Paginator(suffix=None, prefix=None) super().__init__(**options)
async def buffered_send(destination, content, max_length=2000): # use to replace await ctx.send(message) if message could potentially be over the Discord limit of 2000 characters # will split message by \n characters and send in chunks up to max_length size if not content: return paginator = commands.Paginator(prefix='', suffix='', max_size=max_length) for line in content.split('\n'): paginator.add_line(line) for page in paginator.pages: await destination.send(page)