首页 > 解决方案 > discord.ext.commands.errors.ExtensionFailed:NameError

问题描述

我在 discord.py 上使用 cogs 来分离文件,但是有一个错误导致 NameError 并且没有运行。我该如何解决这个问题?

错误

discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.news' raised an error: NameError: name 'news' is not defined.

应用程序.py

...
# Cogs Part
extension = ["cogs.commands","cogs.news", "cogs.manage"]

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        client.load_extension(f'cogs.{filename[:-3]}')
...

齿轮/新闻.py

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

    @commands.command(name='news')
    async def news(self, ctx):
    # ^^^ NameError : name 'news' is not defined


...

标签: discord.py

解决方案


如果您在阅读本文后需要更多帮助,可以加入这个不和谐的小型服务器

不知道你是不是故意漏掉的,但是需要在cogs/news.py文件的最后加上下面的代码。

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

此外,您不需要像以前那样加载扩展,请尝试通过删除以下内容来执行此操作:

扩展 = [“cogs.commands”,“cogs.news”,“cogs.manage”]

像这样:

for file in os.listdir("./cogs"): 
    if file.endswith(".py"): 
        name = file[:-3] 
        client.load_extension(f"cogs.{name}")

如果这些都不起作用,请考虑更换

类新闻(news.Cog):

和:

class news(commands.Cog):

EXTRAS: 您还可以在 app.py 文件中添加一个命令,该命令允许您重新加载 cogs 中的任何命令,而无需重新启动机器人:

@client.command()
@commands.is_owner()
async def reload(ctx, *, name: str):
    try:
        client.reload_extension(f"cogs.{name}")
    except Exception as e:
        return await ctx.send(e)
    await ctx.send(f'"**{name}**" Cog reloaded')

还有一个允许您禁用或启用命令的选项:

@client.command()
@commands.is_owner()
async def load(ctx, *, name: str):
    try:
        client.load_extension(f"cogs.{name}")
    except Exception as e:
        return await ctx.send(e)
    await ctx.send(f'"**{name}**" Cog loaded')

@client.command()
@commands.is_owner()
async def unload(ctx, *, name: str):
    try:
        client.unload_extension(f"cogs.{name}")
    except Exception as e:
        return await ctx.send(e)
    await ctx.send(f'"**{name}**" Cog unloaded')

如果这有任何帮助,将不胜感激并标记为答案:)


推荐阅读