如何在现有Discord.py机器人中整合斜杠命令?
Discord.py 消息事件与斜杠命令共存实现方案
问题背景
原有Discord.py机器人具备指定频道消息过滤、反应触发功能,运行正常。添加斜杠命令后,合并代码导致原有功能与斜杠命令均失效并报错,单独运行斜杠命令则正常。
核心错误原因
- 同时实例化
commands.Bot(命令扩展类)和自定义discord.Client子类,底层冲突无法同时运行 on_message事件未调用await bot.process_commands(),阻塞了斜杠命令的处理流程- 原代码存在语法错误:
message.channel.send漏写await、msg变量未定义、channel1.chat.send写法错误
修正后的完整代码
import discord from discord import app_commands from discord.ext import commands import asyncio # 替换为你的目标频道ID CHANNEL1_ID = 123456789012345678 intents = discord.Intents.default() intents.message_content = True intents.reactions = True # 必须开启才能监听反应事件 # 使用Bot实例统一管理,Bot继承自Client,兼容所有功能 bot = commands.Bot(command_prefix="!", intents=intents) # 标记斜杠命令是否已同步,避免重复操作 bot.tree.sync_done = False @bot.event async def on_ready(): await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name="on my SweetCrispy")) if not bot.tree.sync_done: await bot.tree.sync() bot.tree.sync_done = True print("Ready to roll & rock") @bot.event async def on_message(message): # 优先处理命令,否则会被on_message拦截 await bot.process_commands(message) if message.channel.id == CHANNEL1_ID: if message.author.id == bot.user.id: return if "battle" not in message.content.lower(): await message.delete() await message.channel.send("Are you not ready to battle?") else: # 修复未定义变量和漏写await的问题 sent_msg = await message.channel.send("Let's get ready to battle?") await sent_msg.add_reaction("🤩") @bot.event async def on_reaction_add(reaction, user): if reaction.message.channel.id == CHANNEL1_ID: if user.bot: return if reaction.emoji == "🤩" and reaction.count == 2: # 修复错误的消息发送写法 await reaction.message.channel.send(f"{user.mention} is battle ready") # 注册斜杠命令到Bot自带的命令树 @bot.tree.command(name="battle", description="Score Lookup") async def battle(interaction: discord.Interaction, name: str): await interaction.response.defer(ephemeral=True) await asyncio.sleep(1) await interaction.followup.send(f"custom message here for {name}") # 替换为你的机器人TOKEN bot.run("YOUR_BOT_TOKEN_HERE")
关键注意事项
- 统一实例管理:始终使用
commands.Bot,它继承自discord.Client,天然兼容消息事件、前缀命令和斜杠命令,无需单独创建Client或CommandTree - 命令处理优先级:
on_message中必须先调用await bot.process_commands(message),否则会拦截所有命令请求 - 权限与意图:在Discord开发者后台开启
message_content和reactions意图,否则无法监听对应事件 - 语法严谨性:异步操作必须加
await,变量需提前定义,避免因语法错误导致整个机器人崩溃 - 斜杠命令同步:仅在
on_ready中同步一次斜杠命令,避免重复同步引发的冲突
内容的提问来源于stack exchange,提问作者silentspoonx
相关产品推荐
相关产品推荐

