如何让discord.ext.commands创建的斜杠命令在Discord UI中显示
问题原因
你当前实现的是discord.py的传统前缀命令,即使把前缀设置为/,本质还是基于消息内容解析触发的命令,不属于Discord官方规范的斜杠应用命令(Slash Command),因此不会触发输入框的自动补全弹窗提示。
解决步骤
前置要求
- 确保你的discord.py版本在v2.0及以上,低版本不支持原生斜杠命令,可执行
pip install -U discord.py升级 - 生成机器人邀请链接时,OAuth2授权的scope要同时勾选
bot和applications.commands两个选项,否则命令不会生效
修正后的代码示例
import discord from discord import app_commands from discord.ext import commands # 初始化bot,开启默认权限 intents = discord.Intents.default() bot = commands.Bot(command_prefix="/", intents=intents) # 机器人启动完成后同步斜杠命令到Discord后台 @bot.event async def on_ready(): # 测试阶段可以同步到指定服务器,秒级生效,替换参数为你自己的服务器ID即可 # await bot.tree.sync(guild=discord.Object(id=你的服务器ID)) # 正式上线同步全局命令,最长需要1小时生效 await bot.tree.sync() print(f"已登录为 {bot.user},命令同步完成") # 用@app_commands.command定义斜杠命令,不要使用原来的@bot.command @app_commands.command(name="kick", description="踢出指定用户") @app_commands.checks.has_permissions(kick_members=True) async def kick(interaction: discord.Interaction, member: discord.Member, reason: str = None): await member.kick(reason=reason) # 斜杠命令需要用interaction.response回复,不能使用ctx.send await interaction.response.send_message(f"用户 @{member} 已被踢出。原因:{reason if reason else '无'}") bot.run("你的机器人token")
额外说明
- 斜杠命令的参数会自动在弹窗中显示类型提示、必填标识,不需要额外配置
- 测试阶段优先使用单服务器同步,避免等待全局同步的1小时缓存时间
内容的提问来源于stack exchange,提问作者theheavycoder
相关产品推荐
相关产品推荐

