Discord Slash Command options配置报错create_option未定义排查
问题现象
开发Discord斜杠命令过程中连续遇到导入报错,初始实现代码如下:
import discord import datetime import pickle import os from discord.ext import commands from dislash import * bot = commands.Bot(command_prefix="-") inter_client = InteractionClient(bot, test_guilds=[345328981039382528]) @bot.event async def on_ready(): print("Nick ist online!") @inter_client.slash_command( name="kick", # Defaults to the function name description="kick a user", guild_ids=[345328981039382528], options=[ create_option( name="user", description="Choose a user", option_type=6, required=True ) ] ) async def kick(inter, user:str): pass bot.run("-")
首次运行抛出NameError: name 'create_option' is not defined错误,按照建议添加导入语句from discord_slash.utils.manage_commands import create_option后,又抛出ModulNotFoundError: No module named 'discord_slash'错误,执行pip install discord-py-slash-command时系统提示依赖已安装。
问题原因
- 核心问题是混用了两个完全独立、互不兼容的Discord斜杠命令库:代码初始逻辑基于
dislash库实现,但后续错误引入了另一个库discord-py-slash-command的导入路径,两个库的API、导出方法完全不通用。 - 模块找不到的报错是Python环境不一致导致:在cmd中执行pip安装时,依赖被装到了系统全局Python环境,而运行代码的解释器(比如IDE虚拟环境、其他版本Python)没有安装对应包,因此无法识别。
- 初始的
create_option未定义报错,是因为用from dislash import *通配符导入没有覆盖到该方法,或是安装的dislash版本过旧,方法导出规则有变化。
解决步骤
- 先修复环境不一致问题
不要直接在全局cmd执行pip命令,先激活你运行代码所用的Python环境(比如IDE内置终端、项目虚拟环境),再执行安装命令,避免包装错位置:- 如果平时用
python bot.py启动脚本,就执行python -m pip install dislash.py(dislash的正确包名是dislash.py,和discord-py-slash-command不是同一个包) - 如果确定要换用discord-py-slash-command库,就执行
python -m pip install discord-py-slash-command,同时删掉所有dislash相关代码,禁止两个库混用。
- 如果平时用
- 修正dislash版本的代码(和原有逻辑匹配度最高)
删掉错误添加的from discord_slash.utils.manage_commands import create_option行,把导入部分和参数定义修正为符合dislash规范的写法,不要硬编码option_type的数字值,也不要把用户参数定义为str类型:
import discord import datetime import pickle import os from discord.ext import commands # 显式导入需要的方法,不要用*通配符导入 from dislash import InteractionClient, slash_command, create_option, OptionType bot = commands.Bot(command_prefix="-") inter_client = InteractionClient(bot, test_guilds=[345328981039382528]) @bot.event async def on_ready(): print("Nick ist online!") @inter_client.slash_command( name="kick", description="kick a user", guild_ids=[345328981039382528], options=[ create_option( name="user", description="Choose a user", option_type=OptionType.USER, required=True ) ] ) # 参数类型直接用discord.Member,自动解析为用户对象,不需要传str async def kick(inter, user:discord.Member): await user.kick(reason="斜杠命令踢人") await inter.reply(f"已成功踢出用户 {user.mention}", ephemeral=True) bot.run("替换为你的机器人实际Token")
补充说明:dislash库目前已停止维护,后续新项目可以考虑直接使用discord.py 2.0+版本内置的斜杠命令功能,不需要额外安装第三方交互库。
内容的提问来源于stack exchange,提问作者NoVa Vineuro
相关产品推荐
相关产品推荐

