Discord.py重写自定义帮助嵌入Cog排序命令

时间:2020-10-13 10:05:56

标签: discord.py-rewrite

好,所以我正在使用一个较旧的机器人,并试图重写我的自定义帮助命令,以减少手动操作。但是,我不确定如何使它按预期工作。

我的问题如下:

  1. 它始终以I can't send embeds异常作为响应
  2. 控制台日志中没有错误显示

有人可以帮我解决这个问题吗?

这是我自定义的帮助命令。

    @commands.command(name="help", aliases=["Help", "H", "h"])
    @commands.has_permissions(add_reactions=True, embed_links=True)
    async def help(self, ctx, *cog):
        """Gets all cogs and commands.
        Alt     : h, H, Help
        Usage   : [h]elp <cog or command>"""
        try:
            if not cog:
                """Cog listing.  What more?"""
                embed = discord.Embed(color=discord.Color.dark_gold(), 
                title='Cog Listing and Uncatergorized Commands',
                description=f'Use `{prefix}help <cog>` to find out more about them!\nNote: The Cog Name Must Be in Title Case, Just Like this Sentence.',
                timestamp=ctx.message.created_at)
                embed.set_author(name=self.client.user.name, icon_url=self.client.user.avatar_url)
                cogs_desc = ''
                for x in self.client.cogs:
                    cogs_desc += ('{} - {}'.format(x, self.client.cogs[x].__doc__) + '\n')
                embed.add_field(name='Cogs', value=cogs_desc[0:len(cogs_desc) - 1], inline=False)
                cmds_desc = ''
                for y in self.client.walk_commands():
                    if not y.cog_name and not y.hidden:
                        cmds_desc += ('{} - {}'.format(y.name, y.help) + '\n')
                embed.add_field(name='Uncatergorized Commands', value=cmds_desc[0:len(cmds_desc) - 1], inline=False)
                await ctx.send('', embed=embed)
            else:
                """Helps me remind you if you pass too many args."""
                if len(cog) > 1:
                    embed = discord.Embed(color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
                    embed.set_author(name="Command Failed", icon_url=self.client.user.avatar_url)
                    embed.add_field(name="Error", value="Too many cogs", inline=False)
                    await ctx.send('', embed=embed)
                else:
                    """Command listing within a cog."""
                    found = False
                    for x in self.client.cogs:
                        for y in cog:
                            if x == y:
                                embed = discord.Embed(color=discord.Color.dark_gold(), timestamp=ctx.message.created_at, title=cog[0] + ' Command Listing', description=self.client.cogs[cog[0]].__doc__)
                                for c in self.client.get_cog(y).get_commands():
                                    if not c.hidden:
                                        embed.add_field(name=c.name, value=c.help, inline=False)
                                found = True
                    if not found:
                        """Reminds you if that cog doesn't exist."""
                        embed = discord.Embed(color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
                        embed.set_author(name="Command Failed", icon_url=self.client.user.avatar_url)
                        embed.add_field(name="Error", value='Can not use "' + cog[0] + '"?', inline=False)
                    else:
                        await ctx.send('', embed=embed)
        except:
            await ctx.send("I can't send embeds.")

如果有帮助,我正在使用discord.py-rewrite

-编辑---

由于无数问题,我放弃了上面的代码。并去了下面的代码。我仍然希望它不那么手动,但目前此文章已发布。

    @commands.command(name="Help", aliases=["help", "h", "H"])
    async def _help(self, ctx):
        """Displays all available commands"""
        msg = ctx.message
        await msg.delete()
        contents = [
            f"```css\nAdministrator Commands\n\nBroadcast:  [B]roadcast <message>\nPurge:      [p]urge <1-100>\nBan:        [B]an <user> [reason]\nUnban:      [U]nban <user>\nKick:       [K]ick <user> [reason]\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
            f"```css\nModerator Commands!\n\nAnnounce:   [ann]ounce <message>\nClean:      [C]lean <1-100>\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
            f"```css\nFun Commands\n\nGiphy:      [ ] < >\nTenor:      [ ] < >\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```",
            f"```css\nUtility Commands\n\nPing:       ping\nJoined:     [J]oined [user]\nTopRole:   [top]role [user]\nPerms:      perms [user]\nHelp:       [H]elp [command]\n\nOptional arguments are represented with []\nRequired arguments are represented with <>\nDo not include the [] or <> flags in the command\n ```"
            ]
        pages = 4
        cur_page = 1
        message = await ctx.send(f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
        # getting the message object for editing and reacting

        await message.add_reaction("◀️")
        await message.add_reaction("▶️")

        def check(reaction, user):
            return user == ctx.author and str(reaction.emoji) in ["◀️", "▶️"]
            # This makes sure nobody except the command sender can interact with the "menu"

        while True:
            try:
                reaction, user = await self.client.wait_for("reaction_add", timeout=60, check=check)
                # waiting for a reaction to be added - times out after x seconds, 60 in this
                # example

                if str(reaction.emoji) == "▶️" and cur_page != pages:
                    cur_page += 1
                    await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
                    await message.remove_reaction(reaction, user)

                elif str(reaction.emoji) == "◀️" and cur_page > 1:
                    cur_page -= 1
                    await message.edit(content=f"Page {cur_page}/{pages}:\n{contents[cur_page-1]}")
                    await message.remove_reaction(reaction, user)

                else:
                    await message.remove_reaction(reaction, user)
                    # removes reactions if the user tries to go forward on the last page or
                    # backwards on the first page
            except asyncio.TimeoutError:
                await message.delete()
                break
                # ending the loop if user doesn't react after x seconds

    @_help.error
    async def _help_error(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            guild = ctx.guild
            embed = discord.Embed(
                color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
            embed.set_author(name="Command Failed",
                             icon_url=self.client.user.avatar_url)
            embed.add_field(name="Missing Required arguments",
                            value="Please pass in all required arguments.", inline=False)
            embed.set_thumbnail(url=self.client.user.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await ctx.message.add_reaction(emoji="⚠️️")
            await ctx.message.author.send(embed=embed)
            print("[ERROR] Missing Required Arguments")

        elif isinstance(error, commands.MissingPermissions):
            guild = ctx.guild
            embed = discord.Embed(
                color=discord.Color.dark_red(), timestamp=ctx.message.created_at)
            embed.set_author(name="Access denied",
                             icon_url=self.client.user.avatar_url)
            embed.add_field(name="Insufficient Permissions",
                            value="You do not have permission to use this command.", inline=False)
            embed.set_thumbnail(url=self.client.user.avatar_url)
            embed.set_footer(text=f"{guild.name}", icon_url=guild.icon_url)
            await ctx.message.add_reaction(emoji="?")
            await ctx.message.author.send(embed=embed)
            print("[ERROR] Insufficient Permissions")

但是,是的,如果有人知道如何做到这一点,那么可以从齿轮读取命令,而不是手动将命令键入到help命令的响应中,那么任何提示将非常有帮助。

0 个答案:

没有答案