如何注册Discord.py命令使其在输入时显示并触发指令提示?
实现Discord.py命令的输入提示与正确注册
核心问题说明
你原代码使用的是前缀命令(以!开头),这类命令Discord客户端不会提供输入时的自动提示。要实现输入时弹出命令帮助/补全,必须使用Discord原生支持的应用命令(斜杠命令)(以/开头),这是唯一能触发客户端输入提示的方式。
改造步骤与修正后的代码
1. 依赖检查
确保你的discord.py版本为2.0及以上(仅该版本支持应用命令),版本不足则执行升级:
pip install -U discord.py
2. 完整修正代码
以下代码包含斜杠命令注册、参数提示,同时修复了原代码的逻辑错误:
import discord from discord import appcommands import random import nest_asyncio nest_asyncio.apply() intents = discord.Intents.default() intents.message_content = True # 创建Bot实例 bot = discord.Client(intents=intents) # 初始化命令树,用于注册斜杠命令 tree = appcommands.CommandTree(bot) @bot.event async def on_ready(): print(f'Logged in as {bot.user} (ID: {bot.user.id})') print('------') # 同步命令到Discord(全局同步需1小时生效,测试可指定服务器快速同步) await tree.sync() # 测试用指定服务器同步:替换GUILD_ID为你的服务器ID # await tree.sync(guild=discord.Object(id=GUILD_ID)) # 注册带参数提示的斜杠命令:randomnumber @tree.command(name="randomnumber", description="生成指定数量的随机数") @appcommands.describe(howmuch="要生成的随机数数量(最大4)") async def randomnumber(interaction: discord.Interaction, howmuch: int): if howmuch >=5: await interaction.response.send_message("Are you kidding!?") else: # 一次性生成所有随机数并发送,避免刷屏 random_nums = "\n".join([str(random.random()) for _ in range(howmuch)]) await interaction.response.send_message(f"生成的随机数:\n{random_nums}") # 注册斜杠命令:purge @tree.command(name="purge", description="清理消息(当前已禁用)") async def purge(interaction: discord.Interaction): print("Command disabled.") await interaction.response.send_message("该命令已禁用", ephemeral=True) # 注册斜杠命令:cookie @tree.command(name="cookie", description="发送饼干图片") async def cookie(interaction: discord.Interaction): await interaction.response.send_message("Cookies!") cookie_file = discord.File("cookie.jpg") await interaction.followup.send(file=cookie_file) print("Cookies!") bot.run("你的Bot令牌")
3. 关键改动说明
- 切换为斜杠命令:通过
appcommands.CommandTree注册命令,Discord客户端输入/时会自动列出所有可用命令,输入命令后还会显示参数提示。 - 参数校验与提示:用
@appcommands.describe()给参数添加说明,同时指定howmuch为int类型,Discord会自动校验输入格式,避免原代码中字符串比较的逻辑错误。 - 交互响应逻辑:斜杠命令使用
interaction.response.send_message()回复,后续追加消息用interaction.followup.send(),替代前缀命令的ctx.send()。 - 命令同步:启动时调用
tree.sync()将命令同步到Discord,全局同步生效较慢,测试时可指定服务器快速同步。
4. 原代码逻辑错误修复
- 原
randomnumber中把howmuch当作字符串与"5"比较,会导致逻辑错误(如"10"字符串比较会被判定为小于"5"),现在改为整数类型直接数值比较。 - 原代码循环多次发送消息,改为一次性生成所有随机数再发送,避免频繁刷屏。
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

