如何为discord.py开发的Discord机器人添加Slash命令?
正确的Discord Slash命令实现方案
问题根源
你之前的代码同时初始化了discord.Client和第三方库的interactions.Client,两者属于不同的生态,无法混合使用,这是Slash命令失效的核心原因。当前discord.py v2.x版本已原生支持Slash命令,无需额外依赖第三方库,直接用commands.Bot类即可同时兼容原有消息响应逻辑和Slash命令。
改造后的完整实现
1. 更新bot.py代码
替换原有discord.Client为commands.Bot,整合消息响应和Slash命令逻辑:
import discord from discord import commands import responses async def send_message(message, user_message, is_private): try: response = responses.get_response(user_message) if response == "`PLEASE STOP SWEARING`": await message.author.send(f"{message.author.mention} {response}") await message.channel.send(f"{message.author.mention} {response}") else: await message.author.send(response) if is_private else await message.channel.send(response) print(f"sent {response} to {message.author}") except Exception as e: print(e) def run_discord_bot(): TOKEN = "XXXX" # 初始化commands.Bot,保留原命令前缀,启用消息内容权限 bot = commands.Bot(command_prefix="?", intents=discord.Intents.default()) bot.intents.message_content = True @bot.event async def on_ready(): print(f"{bot.user} is up and running!") # 同步Slash命令到Discord(全局同步需1小时生效,测试可指定服务器ID加速) await bot.tree.sync() print("Slash commands synced successfully!") # 保留原有消息响应逻辑 @bot.event async def on_message(message): if message.author == bot.user: return username = str(message.author) user_message = str(message.content) if responses.get_response(user_message) == "": return elif user_message.startswith("?"): user_message = user_message[1:] await send_message(message, user_message, is_private=True) else: await send_message(message, user_message, is_private=False) # 必须添加此行,否则Slash命令会被消息事件阻塞 await bot.process_commands(message) # 实现指定内容的Slash命令:/rules @bot.tree.command(name="rules", description="显示服务器规则") async def rules(interaction: discord.Interaction): # 替换为你需要发送的自定义内容 custom_content = """ 📜 服务器规则 1. 禁止辱骂、人身攻击他人 2. 遵守Discord官方社区准则 3. 请勿发送垃圾信息或广告 """ await interaction.response.send_message(custom_content) bot.run(TOKEN)
2. 关键注意事项
- 版本要求:确保安装discord.py v2.x及以上版本,执行
pip install -U discord.py更新。 - 命令同步:全局同步Slash命令需约1小时生效,测试时可改为指定服务器同步:
await bot.tree.sync(guild=discord.Object(id=你的服务器ID)),几分钟内即可生效。 - 交互响应:Slash命令必须通过
interaction.response.send_message()回复,这是discord.py原生的交互处理方式。 - 消息事件兼容:
on_message事件末尾必须添加await bot.process_commands(message),否则Slash命令的处理会被阻塞。
3. 清理冗余代码
删除所有涉及interactions库的导入和初始化代码,无需再依赖该第三方库。
验证方法
启动机器人后,在Discord服务器输入/rules,即可触发机器人发送预设的自定义内容。
内容的提问来源于stack exchange,提问作者random dude
相关产品推荐
相关产品推荐

