Discord机器人输入/时内置命令列表不显示问题求助
问题描述
我的Discord机器人遇到一个问题:输入
/符号后,机器人不会出现在内置命令列表中(正常情况此时会显示机器人及所有命令)。机器人的/wew命令功能正常,但命令提示不显示。我是开发新手,希望得到解决建议。
问题原因
- 你当前使用的是discord.py的传统前缀命令(通过
command_prefix='/'设置),这种命令本质是监听消息开头的前缀字符串,Discord官方不会将其识别为内置斜杠命令,因此不会显示在输入/后的命令列表里。 - 命令功能能正常运行,是因为你额外编写了
on_message事件逻辑,手动监听并处理了/wew开头的消息,但这不是官方推荐的斜杠命令实现方式。
解决方案
要让命令显示在Discord的内置命令列表中,需要使用discord.py的**应用命令(Application Commands)**系统,也就是官方斜杠命令。以下是具体修改步骤:
1. 重构命令为官方斜杠命令
替换原有的@bot.command()装饰器为@bot.tree.command(),并添加命令描述;同时迁移原有的参数解析逻辑到斜杠命令的选项中。
2. 同步命令到Discord
机器人启动时需要同步命令到Discord服务器,这样Discord才能识别并展示你的命令。
3. 处理事件冲突(可选)
如果保留on_message事件,必须在事件末尾添加await bot.process_commands(message),否则会影响斜杠命令的执行;或者直接移除on_message的手动处理逻辑,完全依赖斜杠命令的参数解析。
修改后的完整代码示例
import os import discord from discord.ext import commands from discord import app_commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='/', intents=intents, case_insensitive=True) # 机器人启动事件:同步斜杠命令 @bot.event async def on_ready(): print(f"已登录为 {bot.user}") # 同步全局命令(全局生效需要1小时左右),测试服务器可替换为 guild=discord.Object(id=你的服务器ID) 快速同步 await bot.tree.sync() print("斜杠命令已同步") # 定义官方斜杠命令 /wew @bot.tree.command(name="wew", description="自定义wew命令") @app_commands.describe( number="序号", target="提及的用户或用户ID", field2="第二个字段内容", field3="第三个字段内容", field4="第四个字段内容", field5="第五个字段内容" ) async def wew_command(interaction: discord.Interaction, number: str, target: str, field2: str, field3: str, field4: str, field5: str): # 处理提及用户逻辑 if target.isnumeric(): mention = target else: # 提取用户ID user_id = target.strip().strip('<@!>').strip('<@').strip('>') try: mentioned_user = await bot.fetch_user(user_id) mention = mentioned_user.mention if mentioned_user else f"<@{user_id}>" except: mention = f"<@{user_id}>" # 构建Embed block_title = f"№ {number.strip()}" embed = discord.Embed(title=block_title, color=0x000000) embed.add_field(name="\u200B", value=f"**1. _____________ {mention}**", inline=False) embed.add_field(name=f"**_________** {field2}", value="", inline=False) embed.add_field(name=f"**_________** {field3}", value="", inline=False) embed.add_field(name=f"**_________** {field4}", value="", inline=False) embed.add_field(name=f"**_________** {field5}", value="", inline=False) embed.add_field(name="\u200B", value=f"**_________** {interaction.user.mention}") # 发送消息 await interaction.response.send_message(embed=embed) # 若保留on_message事件,必须添加process_commands,否则斜杠命令失效 @bot.event async def on_message(message): # 可保留原有逻辑,建议迁移到斜杠命令后删除 if message.author != bot.user and message.content.startswith('/wew'): pass # 必须添加此行 await bot.process_commands(message) token = '_______' # keep_alive() # 若使用了keep_alive函数则保留 bot.run(token)
额外说明
- 测试服务器中,可将
await bot.tree.sync()改为await bot.tree.sync(guild=discord.Object(id=你的服务器ID)),实现命令立即生效。 - 斜杠命令的参数由Discord自动解析,无需手动拆分字符串,比
on_message方式更规范,符合Discord官方使用习惯。 - 原代码中未用到的
interactions库可删除,减少不必要的依赖。
内容的提问来源于stack exchange,提问作者qweq
相关产品推荐
相关产品推荐

