【问题标题】:discord.py: problem when help command not have cog mentioned in the codediscord.py:当帮助命令在代码中没有提到 cog 时出现问题
【发布时间】:2021-03-24 00:43:55
【问题描述】:

我的代码:

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))

当我运行这段代码时,机器人必须发送提到的 cogs 但是如果代码中提到的其他 cog 中的一个 cog 是“离线”或者 cog 文件没有 存在所有代码都行不通。

错误:

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

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

我该怎么做?

【问题讨论】:

    标签: python python-3.x discord.py python-3.8


    【解决方案1】:

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

    我们可以做的是为它添加一个检查,如果用户没有指定一个 cog,它会全部取走。如果 cog 被卸载,它会抛出一个错误,因为 self.bot.get_cog(cog)=NoneType object 我们可以改用 try 和 except

        @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)
    

    【讨论】:

    • 感谢您的解释,我打算做类似的事情,但我不知道从哪里开始,事实上,当我尝试做 cog = None 时,它给出了一个错误。非常感谢
    猜你喜欢
    • 2021-06-29
    • 2019-03-17
    • 2020-11-06
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2020-12-18
    • 2021-01-01
    相关资源
    最近更新 更多