discord.py - 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
...
解决方案
如果您在阅读本文后需要更多帮助,可以加入这个不和谐的小型服务器。
不知道你是不是故意漏掉的,但是需要在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')
如果这有任何帮助,将不胜感激并标记为答案:)
推荐阅读
- java - 在 Java Stream for Array List 中实现 for 循环?
- c - 为什么基本 GType 类型的 instance_size 为 0?
- php - 如何只有一个处理文件用于多个 AJAX 调用
- google-colaboratory - Colab 专业会议有时会在拟合模型的过程中中断,我是否达到了资源限制?
- go - 谷歌云存储是否有 fs.ReadDir 的 Go 实现?
- javascript - Array.indexOf 不是函数
- php - PHP Laravel 类返回几个具有静态属性的类 - 静态类中的 C# 静态类
- django - 单击按钮时运行视图
- jmeter - JMeter - 如何修改/增加响应超时
- r - 如何在数据框 (R) 中删除一个级别以进行进一步的统计分析