我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用discord.ext.commands.Paginator()。
def sh(self, ctx, *, command): """Execute a system command. Bot owner only.""" command = command.split(" ") process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) try: output, errors = process.communicate(timeout=8) output = output.split("\n") process.terminate() except subprocess.TimeoutExpired: process.kill() output = ["Command timed out. x.x"] paginator = commands.Paginator(prefix="```bash") for line in output: paginator.add_line(line) for page in paginator.pages: await ctx.send(page)
def _geval(self, ctx, expression, type_=None): """Evaluate an expression.""" try: if type_ == "await": output = await eval(expression) elif type_ == "exec": output = exec(expression) else: output = eval(expression) output = str(output) except Exception as error: output = f"x.x An error has occurred: {error}" paginator = commands.Paginator(prefix="```py", max_size=500) for index in range(0, len(output), 490): paginator.add_line(output[index:index+490]) for page in paginator.pages: await ctx.send(page)
def multiban(self, ctx, reason, delete_days: DeleteDays=2, *members: converters.RawMember): """ Bans multiple users. Functions similarly to d?ban. """ progress = await ctx.send(f'Banning {len(members)} member(s)...') reason = reason or 'No reason provided.' paginator = commands.Paginator(prefix='', suffix='') for member in members: try: await ctx.guild.ban(member, delete_message_days=delete_days, reason=f'(Multi-banned by {ctx.author}) {reason}') paginator.add_line(f'{ctx.green_tick} Banned {describe(member)}.') except discord.NotFound: # XXX: This code path might be unreachable, research further paginator.add_line(f"{ctx.red_tick} {describe(member)} wasn't found.") except discord.HTTPException: paginator.add_line(f'{ctx.red_tick} Failed to ban {describe(member)}. No permissions?') await progress.delete() for page in paginator.pages: await ctx.send(page)
def permissions(self, ctx): """ Views my permissions in this server. This does not view my permissions in this channel. In other words, channel permission overwrites are not taken into account here. """ perms = ctx.guild.me.guild_permissions paginator = commands.Paginator() max_perm_length = max(len(checks.beautify_permission_name(p[0])) for p in perms) for attr, value in perms: indicator = '\U00002705' if value else '\U0000274c' paginator.add_line(f'{checks.beautify_permission_name(attr): <{max_perm_length}} {indicator}') for page in paginator.pages: await ctx.send(page)
def quotelist(self, ctx, *show_pages: int): """List all the quotes. Usage: quotelist""" if not self.bot.store['quotes']: await ctx.send('There are no quotes. Add some first!') return rshow_pages = [i for i in show_pages] pager = commands.Paginator(prefix='', suffix='', max_size=1595) if not show_pages: show_pages = (1,) for n, i in enumerate(self.bot.store['quotes']): qout = quote.qrender(i, n, self.bot) pager.add_line(qout) for page_n in show_pages: try: await ctx.send('**__Listing page *{0}* of *{1}* of quotes.__**\n'.format(page_n, len(pager.pages)) + pager.pages[page_n - 1]) except IndexError: await ctx.send('**__Error: page *{0}* doesn\'t exist! There are *{1}* pages.__**'.format(page_n, len(pager.pages)))
def charinfo(self, ctx, *, uchars: str): """Get the Unicode info for a character or characters. Usage: charinfo [character(s)]""" no_preview = [ '\u0020', '\uFEFF' ] cinfo = commands.Paginator(prefix='', suffix='', max_size=(1999 if self.bot.selfbot else 2000)) for char in list(uchars.replace('\n', '')): hexp = str(hex(ord(char))).replace('0x', '').upper() while len(hexp) < 4: hexp = '0' + hexp preview = f' (`{char}`)' cinfo.add_line(f'U+{hexp} {unicodedata.name(char)} {char}' + (preview if char not in no_preview else '')) if len(cinfo.pages) > 5: await ctx.send('Too long, trimming to 5 pages.') for page in cinfo.pages[0:5]: await ctx.send(page)
def source(self, ctx, *, command: BotCommand): """Displays the source code for a particular command. There is a per-user, 2 times per 5 seconds cooldown in order to prevent spam. """ paginator = commands.Paginator(prefix='```py') for line in inspect.getsourcelines(command.callback)[0]: # inspect.getsourcelines returns the lines with the newlines at the # end. However, the paginator will add it's own newlines when joining # up the lines. We don't want to have double lines. So we have to # strip off the ends. # # Also, because we prefix each page with a code block (```), we need # to make sure that other triple-backticks don't prematurely end the # block. paginator.add_line(line.rstrip().replace('`', '\u200b`')) for p in paginator.pages: await ctx.send(p) # Credits to Reina
def emitter(self): while not self.closed: now = time.monotonic() send_delta = now - self._last_emit if send_delta < 5: await asyncio.sleep(5 - send_delta) self._last_emit = time.monotonic() paginator = commands.Paginator(prefix='', suffix='') for chunk in self._buffer: paginator.add_line(chunk.strip()) self._buffer.clear() self._can_emit.clear() for page in paginator.pages: await self.webhook.execute(page) await self._can_emit.wait()
def cmds(self, ctx): """Show all custom commands.""" if ctx.invoked_subcommand is None: ttl = None if ctx.message.content.endswith(' stay') else 20 p = commands.Paginator(prefix='```css') cmds = read_json("commands") p.add_line('[List of Custom Commands]') msg = [] for cmd in sorted(cmds): msg.append(cmd) if cmd == list(sorted(cmds))[-1] or len(msg) % 5 == 0 and len(msg) != 0: p.add_line(', '.join(x for x in msg)) msg = [] for page in p.pages: await ctx.send(page, delete_after=ttl) await ctx.message.delete() # List all custom commands with Links
def cat_facts(self, ctx, count: integer = 1): """Get cat facts. 1 <= [count] <= 20 """ count = between(count, 1, 20) partial = count - int(count) count = int(count) if partial: count += 1 elif count == 0: return try: facts = await self.fetch_facts(count) except NotFound as e: facts = [str(e)] else: if partial: end_ind = int(len(facts[-1]) * partial) facts[-1] = facts[-1][:end_ind] or facts[-1][0] if len(facts) > 1: msg = commands.Paginator(prefix='', suffix='') for ind, fact in enumerate(facts): msg.add_line(f'{ind + 1}. {fact}') for page in msg.pages: await ctx.send(page) else: await ctx.send(facts[0])
def send_error(dest, ctx, exc, num): msg = f'{ctx.message.content}\nin {"guild" if ctx.guild else "DM"}' tb = ''.join(traceback.format_exception(*tb_args(exc))).replace(UPPER_PATH, '...') pag = commands.Paginator(prefix=f'{num} {msg}\n```') for line in tb.split('\n'): pag.add_line(line) for page in pag.pages: await dest.send(page)
def commandstats(self): p = commands.Paginator() counter = self.bot.commands_used 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 self.bot.say(page)
def roleinfo(self, ctx, *, role: str): """Display information about a role. * role - The role to display information about.""" role = await helpers.role_by_substring(ctx, role) embed = discord.Embed(title=role.name) embed.colour = role.color embed.description = f"{role.id} | Members: {len(role.members)}" embed.add_field(name="Color", value=f"{role.color}", inline=False) if role.permissions.administrator: embed.add_field(name="Administrator", value=True) else: paginator = commands.Paginator(prefix="", suffix="") for permission, value in role.permissions: if value: paginator.add_line(str(permission).capitalize().replace("_", " ")) for page in paginator.pages: embed.add_field(name="Permissions", value=page) await ctx.send(embed=embed)
def paginate(data): paginator = commands.Paginator() for i in data.splitlines(): paginator.add_line(i) return paginator.pages
def fontlist(self, ctx): """List the available fancy character sets / alphabets / fonts. Usage: fonts""" pager = commands.Paginator(prefix='', suffix='') pager.add_line('**Listing all character sets defined with samples.**') for i in self.al_aliases: tmp = self.stylize(i, 'abcdefghijklmnopqrstuvwxyz') pager.add_line('**{0}**: `{1}`'.format(i, tmp)) pager.add_line('**Invoke with `[p][name of set] [message here]`.** For example: `!math_bold hello world`.') for page in pager.pages: await ctx.send(page)
def list(self, ctx): """List the substitutions. Usage: sub list""" if len(self.bot.store['subs']) >= 1: pager = commands.Paginator(prefix='', suffix='') pager.add_line('Here are your substitutions:') for idx, (name, replacement) in enumerate(self.bot.store['subs'].items()): pager.add_line('`#' + str(idx + 1) + '`: ' + name + ' ? ' + replacement) for page in pager.pages: await ctx.send(page) else: await ctx.send('You don\'t have any substitutions!')
def guildlist(self, ctx): """List the guilds I am in. Usage: guildlist""" echeck_perms(ctx, ('bot_owner',)) pager = commands.Paginator() for guild in self.bot.guilds: pager.add_line(guild.name) for page in pager.pages: await ctx.send(page)
def emit(self, record: logging.LogRecord): if record.levelno != self.level: return # only log the handlers level to the handlers channel, not above msg = self.format(record) start = msg.find('```py\n') if start != -1: msg, trace = msg[:start], msg[start:] else: trace = None # the actual log message for line in msg.split('\n'): # if this is a small codeblock and goes over multiple messages it will break out # so we check that each chunk (besides the first) starts and stops with a backtick for idx, chunk in enumerate(line[x:x + 1994] for x in range(0, len(line), 1994)): # ugh if not chunk.endswith('`'): chunk = f'{chunk}`' if not chunk.startswith('`'): chunk = f'`{chunk}' self._buffer.append(chunk) # the traceback, sent separately to be in a big codeblock for syntax highlighting if trace is not None: # cut off the original codeblock trace = trace[6:-3] paginator = commands.Paginator(prefix='```py\n', suffix='```') for line in trace.split('\n'): for chunk in (line[x:x + 1987] for x in range(0, len(line), 1987)): paginator.add_line(chunk) for page in paginator.pages: self._buffer.append(page) self._can_emit.set()
def long(self, ctx): """Display also their content""" ttl = None if ctx.message.content.endswith(' stay') else 20 p = commands.Paginator(prefix='```css') cmds = read_json("commands") 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=ttl) await ctx.message.delete()
def trivia(self, ctx): """Ask a random trivia question.""" async with ctx.bot.session.get(URL_TRIVIA_API) as response: if response.status == 200: data = await response.json() trivia = data["results"][0] correct_answer = html.unescape(trivia["correct_answer"]) incorrect_answers = [] for answer in trivia["incorrect_answers"]: incorrect_answers.append(html.unescape(answer)) choices = [correct_answer] + incorrect_answers systemrandom.shuffle(choices) embed = discord.Embed() embed.title = html.unescape(trivia["category"]) embed.description = html.unescape(trivia["question"]) difficulty = html.unescape(trivia["difficulty"]).capitalize() footer_text = f"Powered by Open Trivia DB | Difficulty: {difficulty}" embed.set_footer(text=footer_text) paginator = commands.Paginator(prefix="```markdown") for index in range(len(choices)): paginator.add_line(f"{index+1}. {choices[index]}") embed.add_field(name="Options", value=paginator.pages[0]) await ctx.send(ctx.author.mention, embed=embed) choice = await input_number(ctx, "Answer by number in 15 seconds.", timeout=15, min_value=1, max_value=len(choices)) if choices[choice-1] == correct_answer: await ctx.send("Correct! :3") else: await ctx.send(f"Nope, the correct answer is {correct_answer}. :<") else: await ctx.send("Could not fetch trivia. :<")
def format(self): """A modified copy of Discord.py rewrite's vanilla HelpFormatter.format().""" self._paginator = Paginator() # we need a padding of ~80 or so description = self.command.description if not self.is_cog() else inspect.getdoc(self.command) if description: # <description> portion self._paginator.add_line(description, empty=True) if isinstance(self.command, Command): # <signature portion> signature = self.get_command_signature() self._paginator.add_line(signature, empty=True) # <long doc> section if self.command.help: self._paginator.add_line(self.format_help(self.command.help), empty=True) # end it here if it's just a regular command if not self.has_subcommands(): self._paginator.close_page() return self._paginator.pages max_width = self.max_name_size def category(tup): cog = tup[1].cog_name # we insert the zero width space there to give it approximate # last place sorting position. return cog + ':' if cog is not None else '\u200bCommands:' filtered = await self.filter_command_list() if self.is_bot(): data = sorted(filtered, key=category) for category, commands in itertools.groupby(data, key=category): # there simply is no prettier way of doing this. commands = sorted(commands) if len(commands) > 0: self._paginator.add_line(category) self._add_subcommands_to_page(max_width, commands) else: filtered = sorted(filtered) if filtered: self._paginator.add_line('Commands:') self._add_subcommands_to_page(max_width, filtered) # add the ending note self._paginator.add_line() ending_note = self.get_ending_note() self._paginator.add_line(ending_note) return self._paginator.pages
def roles(self, ctx): """ Views detailed information about the roles in this server. Information is presented in a table-like layout. Columns: - Role position The role's position in the hierarchy. The bottom role is #0. - Role name - Role color - Role ID - Role properties - Role members Role properties: Role properties are represented as a sequence of characters. Each character has a separate meaning. H: This role is hoisted. M: This role is managed. @: This role is mentionable by everyone. D: This role is the default role (@everyone). A: This role has the "Administrator" permission. E: This role has the "Mention Everyone" permission. """ paginator = commands.Paginator() sorted_roles = sorted(ctx.guild.roles, key=lambda r: r.position, reverse=True) longest_role_name = max(map(lambda r: len(r.name), ctx.guild.roles)) # add lines for role in sorted_roles: # compile a list of role properties attrs = { # role attributes 'H': role.hoist, 'M': role.managed, '@': role.mentionable, 'D': role.is_default(), # role permissions 'A': role.permissions.administrator, 'E': role.permissions.mention_everyone } properties = ''.join(rep for rep, val in attrs.items() if val) # how many members? members = utils.commas(len(role.members)) # get color color = 'default' if role.color == discord.Color.default() else str(role.color) fmt = (f'{role.position: <2} {role.name: <{longest_role_name}} {color} {role.id: <18} ' f'{properties: <{len(attrs)}} {members: <4}') paginator.add_line(fmt) for page in paginator.pages: await ctx.send(page)
def archive(self, ctx, user: discord.User, amount: int, *, flags: converters.Flags={}): """ Fetches logged messages from a user. Only Dogbot Moderators can do this. The amount you specify is not equal to the amount of messages that will be shown to you. Rather, it will be the amount of messages that are fetched from the bot's database. Flags allow you to specify which messages you want to see, or how you want to see them. For more information, see https://github.com/slice/dogbot/wiki/Message-Logging. """ async with ctx.acquire() as conn: fetch_sql = """ SELECT * FROM messages WHERE author_id = $1 AND guild_id = $2 ORDER BY created_at DESC LIMIT $3 """ messages = await conn.fetch(fetch_sql, user.id, ctx.guild.id, amount) paginator = commands.Paginator() flag_processors = { 'has-attachments': lambda value, msg: json.loads(msg['attachments']), 'contains': lambda value, msg: value in msg, 'edited': lambda value, msg: msg['edited'], 'deleted': lambda value, msg: msg['deleted'], 'channel': lambda value, msg: msg['channel_id'] == int(value), 'mentions': lambda value, msg: re.search(f'<@!?{value}>', content) is None } # add messages for msg in messages: content = msg['new_content'] or msg['original_content'] failed_flags = False for flag_name, processor in flag_processors.items(): if flag_name in flags and not processor(flags[flag_name], msg): failed_flags = True if not failed_flags: paginator.add_line(format_record(msg, flags)) # send pages if not paginator.pages: return await ctx.send('```No results.```') for page in paginator.pages: await ctx.send(page)