如何像示例那样展示Discord机器人指令?API更新后指令失效求助
问题解决思路
核心问题分析
你的代码存在两个关键问题,导致指令无法正常运行:
- 函数名拼写错误:定义的函数是
shutown,但添加命令时用的是shutdown,名称不匹配。 - 装饰器与API适配问题:使用了未绑定到bot实例的
@commands.command(),且最新Discord API更推荐使用斜杠指令而非传统前缀指令。
修复方案(两种可选)
方案1:修复传统前缀指令
修正拼写错误和装饰器,适配现有写法:
import discord from discord.ext import commands # 必须启用必要的intents,新版API要求 bot = commands.Bot(command_prefix="/", intents=discord.Intents.all()) @bot.event async def on_ready(): print('Ready!') await bot.change_presence(activity=discord.Streaming(name="test", url="My url")) # 使用绑定到bot的装饰器,自动注册指令 @bot.command() async def shutdown(ctx): print("tests") await ctx.send("good bye 😪") await ctx.bot.close() # 新版推荐用close()替代logout()
方案2:改用官方推荐的斜杠指令(适配最新API)
Discord API更新后,斜杠指令是官方主推的交互方式,代码示例:
import discord from discord import app_commands bot = discord.Client(intents=discord.Intents.all()) tree = app_commands.CommandTree(bot) @bot.event async def on_ready(): print('Ready!') await bot.change_presence(activity=discord.Streaming(name="test", url="My url")) await tree.sync() # 同步斜杠指令到Discord服务器 @tree.command(name="shutdown", description="关闭机器人") async def shutdown(interaction: discord.Interaction): print("tests") await interaction.response.send_message("good bye 😪") await bot.close()
额外注意事项
- 确保discord.py版本为v2.x以上,可通过
pip install -U discord.py更新。 - 在Discord开发者后台启用机器人所需的intents(如消息内容、服务器成员等),并赋予对应权限。
内容的提问来源于stack exchange,提问作者Wokia12
相关产品推荐
相关产品推荐

