Python实现Discord斜杠命令遇问题:报错及命令不显示求助
Discord Python斜杠命令问题解决方案
一、AttributeError: module 'discord' has no attribute 'Bot' 错误解决
这个错误是因为你的discord.py版本过低导致的。discord.Bot是discord.py v2.0及以上版本才新增的专用斜杠命令机器人类,旧版(v1.x)的discord.py里没有这个属性。
解决步骤:
- 升级discord.py到最新稳定版:
pip install -U discord.py
- 升级后,原代码可调整为(
discord.Bot无需command_prefix参数,且必须指定intents):
import discord bot = discord.Bot(intents=discord.Intents.default()) @bot.slash_command(name="first_slash", guild_ids=[你的服务器ID]) # 指定服务器ID可立即同步命令 async def first_slash(ctx): await ctx.respond("你执行了斜杠命令!") bot.run("你的机器人令牌")
如果坚持使用commands.Bot,v2.x版本的commands.Bot也支持slash_command装饰器,代码示例:
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.default()) @bot.slash_command(name="first_slash", guild_ids=[你的服务器ID]) async def first_slash(ctx): await ctx.respond("你执行了斜杠命令!") bot.run("你的机器人令牌")
二、无报错但Discord端不显示斜杠命令的问题解决
你使用的discord_slash库已停止维护,存在同步延迟、权限兼容等问题,推荐直接使用discord.py官方内置的斜杠命令支持。若暂时要排查该库的问题,可检查以下几点:
- 指定服务器ID:全局命令需等待约1小时同步到所有服务器,添加
guild_ids参数可让命令立即在目标服务器生效:
@slash.slash(name="test", guild_ids=[你的服务器ID]) async def _test(ctx: SlashContext): await ctx.send("Hello World!")
- 检查机器人权限:确保机器人在服务器中拥有
applications.commands权限,邀请机器人时需使用包含scope=bot+applications.commands的授权链接。 - 替换为官方实现:废弃
discord_slash,改用discord.py v2.x的内置斜杠命令方案(参考第一部分代码)。
内容的提问来源于stack exchange,提问作者Angadpal Tak
相关产品推荐
相关产品推荐

