2

我的代码:

import discord
from discord.ext import commands
import re
import os

class Help2(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    

    @commands.command()
    async def help2(self, ctx, * cog=None):
        embed = discord.Embed(title=f"Command of {self.bot.user.name}", description=f"Prefix = {self.bot.command_prefix}\n*Per avere maggiori informazioni su ogni comando digita `{self.bot.command_prefix}help <nome comando>`.*")
        
        for command in self.bot.get_cog("Ban").get_commands():
            embed.add_field(name=f"{command.name} - {command.description}.", value=f"↳ **Syntax:** `{command.usage}`")

        for command in self.bot.get_cog("Kick").get_commands():
            embed.add_field(name=f"{command.name} - {command.description}.", value=f"↳ **Syntax:** `{command.usage}`")

        for command in self.bot.get_cog("Unban").get_commands():
            embed.add_field(name=f"{command.name} - {command.description}.", value=f"↳ **Syntax:** `{command.usage}`")
        
        await ctx.send(embed=embed)



    @help2.error
    async def help2_error(self, ctx, error):
        await ctx.send(f"```{error}```")


def setup(bot):
    bot.add_cog(Help2(bot))

当我运行此代码时,机器人必须发送提到的 cog,但是如果代码中提到的其他 cog 中的一个 cog 是“脱机”或 cog 文件不存在,则所有代码都不起作用。

错误:

Command raised an exception: AttributeError: 'NoneType' object has no attribute 'get_commands'

即使一个或多个齿轮“离线”或仅提及在线齿轮,我也希望代码运行

我该怎么做?

4

1 回答 1

2

该参数*cog作为跟随您的命令的单词元组传递,如果您尝试,则会引发错误*cog=None

相反,我们可以做的是为它添加一个检查,如果用户没有指定一个 cog,它就会全部接受。如果 cog 被卸载,它会抛出一个错误,因为self.bot.get_cog(cog)=NoneType object我们可以使用tryandexcept

    @commands.command()
    async def help2(self, ctx, *cog):
        embed = discord.Embed(title=f"Command of {self.bot.user.name}", description=f"Prefix = {self.bot.command_prefix}\n*Per avere maggiori informazioni su ogni comando digita `{self.bot.command_prefix}help <nome comando>`.*")

        if len(cog)==0:
            cog = ("Ban", "Kick", "Unban")
        
        for i in cog:
            try:
                for command in self.bot.get_cog(i).get_commands():
                    embed.add_field(name=f"{command.name} - {command.description}.", value=f"↳ **Syntax:** `{command.usage}`")
            except:
                pass # What will happen if cog is unloaded, or nothing with pass
        
        await ctx.send(embed=embed)
于 2020-12-13T01:01:59.173 回答