如何升级现有Discord机器人以支持斜杠命令(可保留原有命令)
快速升级方案
discord.py自带的app_commands模块就是官方支持斜杠命令的工具,完全不用从零开发。你可以把原有on_message里的命令逻辑抽成独立函数,直接复用这些核心逻辑,只需要用app_commands.command()装饰器把函数注册成斜杠命令就行,不用重写功能代码。
斜杠命令与原有文本命令共存的实现
两者天然就能共存,不需要额外处理:
- 保留你原来的
on_message代码,文本命令会正常触发 - 注册的斜杠命令由Discord官方直接触发,不会走
on_message流程,所以不会和原有逻辑冲突 - 注意在
on_message开头加上if message.author.bot: return,避免机器人自己触发命令
斜杠命令代码模板
下面是一个完整的示例,包含原有文本命令、斜杠命令注册、命令同步的核心代码:
import discord from discord.ext import commands from discord import app_commands # 初始化机器人,开启必要的intents intents = discord.Intents.default() intents.message_content = True # 用于处理原有文本命令的消息内容 bot = commands.Bot(command_prefix="!", intents=intents) # --- 原有文本命令逻辑(保留不动)--- @bot.event async def on_message(message): if message.author.bot: return # 示例:原有!ping命令 if message.content.strip().startswith("!ping"): await message.channel.send("Pong!") # 其他原有复杂命令逻辑... # 如果你之前用了commands.Bot的@bot.command()装饰器,需要保留这行 await bot.process_commands(message) # --- 斜杠命令部分 --- # 示例:注册/ping斜杠命令 @bot.tree.command(name="ping", description="返回Pong!的响应") async def ping_slash(interaction: discord.Interaction): # 这里可以直接调用你原有封装好的逻辑函数,比如: # await your_existing_ping_logic(interaction.channel) await interaction.response.send_message("Pong!") # 示例:带参数的斜杠命令(比如打招呼) @bot.tree.command(name="greet", description="向指定用户打招呼") @app_commands.describe(user="要打招呼的用户") async def greet_slash(interaction: discord.Interaction, user: discord.Member): await interaction.response.send_message(f"你好,{user.mention}!") # 同步斜杠命令到服务器 @bot.event async def on_ready(): print(f"已登录:{bot.user.name}") # 全局同步(所有服务器生效,可能需要1小时左右) await bot.tree.sync() # 测试用:指定单个服务器同步(立即生效) # test_guild = discord.Object(id=1234567890) # 替换成你的服务器ID # await bot.tree.sync(guild=test_guild) # 启动机器人 bot.run("你的机器人TOKEN")
注意点:
- 必须在开发者门户开启机器人的
Message Content Intent,否则无法读取文本命令的消息内容 - 斜杠命令的响应要用
interaction.response.send_message(),和原有message.channel.send()的用法略有不同 - 全局同步命令需要等待Discord服务器生效,测试时建议用指定服务器同步
可靠的教程推荐
优先看discord.py官方文档的app_commands章节,里面覆盖了所有斜杠命令的核心用法,包括子命令、选项类型、权限控制、错误处理等,是最权威的参考。另外可以查看discord.py官方仓库的examples文件夹,里面有完整的斜杠命令示例代码,能快速上手各种场景。
内容的提问来源于stack exchange,提问作者Imaginary
相关产品推荐
相关产品推荐

