py-cord开发Discord机器人报错NameError: name 'Option' is not defined
报错原因
NameError: name 'Option' is not defined的触发原因非常直接:代码中调用了Option类定义斜杠命令参数,但没有提前将该类导入当前代码的命名空间,和是否加载扩展、是否使用预发布版本无关联。
py-cord 2.x全版本(含预发布版)中,斜杠命令参数所用的Option类归属discord.commands模块,常规import discord、from discord.ext import commands导入操作不会自动将该类加载到当前可直接调用的命名空间,直接引用就会抛出名称未定义的错误。
修复方案
二选一即可,不需要改动其他业务逻辑:
- 方案1:补充导入语句
在文件头部的导入区域新增一行Option的导入代码,修改后的导入段如下:
import discord from discord import Option # 新增这行即可 from discord.ext import commands bot = discord.Bot() # 后续原有代码无需调整
- 方案2:写全类的调用路径
如果不想单独导入Option,可以在参数定义时直接写全类的完整引用路径,将所有Option(替换为discord.Option(即可,示例代码片段:
@bot.slash_command(guild_ids=[...]) async def hello( ctx: discord.ApplicationContext, name: discord.Option(str, "Enter your name"), age: discord.Option(int, "Enter your age", min_value=1, max_value=99, default=18) ): await ctx.respond(f"Hello! Your name is {name} and you are {age} years old.")
注意:不要从
discord.ext.commands路径导入Option,该路径下的类为旧版本兼容遗留内容,会导致斜杠命令参数校验、默认值配置等功能异常。
内容的提问来源于stack exchange,提问作者BurAndBY
相关产品推荐
相关产品推荐

