Discord.py斜杠命令预览不显示问题求助
解决Discord.py机器人斜杠命令不显示预览的问题
你当前的问题核心是:用@bot.command定义的是前缀命令——哪怕把前缀设为/,它本质还是依赖消息内容解析触发的传统命令,Discord不会为这类命令提供输入时的预览列表。只有Discord官方的**应用命令(斜杠命令)**才会出现在/输入时的预览里,也就是discord.py中通过bot.tree相关装饰器定义的命令。
具体修改步骤
1. 替换命令定义方式
把原来的@bot.command装饰器换成@bot.tree.command,同时调整命令的触发逻辑:
- 函数参数从
ctx改为interaction - 回复使用
await interaction.response.send_message()代替await ctx.send()
2. 确保命令同步生效
on_ready里的await bot.tree.sync()必须执行,它会把你的斜杠命令同步到Discord服务器。如果是测试服务器,建议指定服务器ID来快速同步(全局同步需要约1小时)。
修改后的完整代码示例
import discord import os from discord.ext import commands from dotenv import load_dotenv from datetime import datetime, timezone load_dotenv() __TOKEN = os.getenv('DISCORD_TOKEN') intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='/', intents=intents) # 替换成你的测试服务器ID,加快命令同步速度(可选) TEST_GUILD_ID = discord.Object(id=123456789012345678) active_channel = 'testing' @bot.event async def on_ready(): try: print(f'Signed in as { bot.user }') # 同步到指定测试服务器,立即生效 await bot.tree.sync(guild=TEST_GUILD_ID) # 全局同步用 await bot.tree.sync(),需等待约1小时 print(f"Successfully synced commands.") except Exception as e: print(e) @bot.event async def on_message(message): if message.author == bot.user: return # 修正频道判断逻辑:用频道名称匹配字符串 if message.channel.name == active_channel: if 'uncle terry' in message.content.lower(): await message.channel.send('Hi') await bot.process_commands(message) # 定义斜杠命令:ping,description会显示在预览中 @bot.tree.command(name='ping', description='回复pong') async def ping(interaction: discord.Interaction): await interaction.response.send_message('pong') # 定义斜杠命令:time @bot.tree.command(name='time', description='显示当前UTC时间') async def time(interaction: discord.Interaction): await interaction.response.send_message(f"It is {datetime.now(timezone.utc)} UTC.") bot.run(__TOKEN)
额外说明
- 斜杠命令必须设置
description参数,该描述会直接展示在预览列表里 - 原来的前缀命令可以保留,依然能正常触发,但不会出现在预览中;如果不需要前缀命令,可删除
command_prefix参数和process_commands调用 - 若测试时命令未显示,重启机器人并确认
bot.tree.sync()执行成功,或等待几分钟(全局同步速度较慢)
内容的提问来源于stack exchange,提问作者Yeonari
相关产品推荐
相关产品推荐

