You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 如何将指定命令限制为仅斜杠命令?

解决方案

核心问题

你用了hybrid_command装饰器,它的本质就是同时注册前缀命令和斜杠命令,所以无论怎么拦截消息,前缀调用都会被触发。要做纯斜杠命令,必须放弃hybrid_command,改用纯应用命令实现。

具体步骤

  1. 替换命令装饰器
    把@client.hybrid_command换成@client.tree.command,同时用discord.app_commands.guild_only()替代@commands.guild_only()(应用命令的权限装饰器和前缀命令不通用)。

  2. 同步应用命令
    斜杠命令需要同步到Discord服务器才能生效,在机器人启动时添加同步逻辑。

  3. 移除无效的on_message拦截
    纯斜杠命令不会响应消息前缀调用,之前的on_message事件完全不需要保留。

修改后的完整代码

import discord
from discord import app_commands

# 机器人客户端初始化(根据你的实际情况调整)
client = discord.Client(intents=discord.Intents.default())
tree = app_commands.CommandTree(client)

# 你的Modal定义(保持原有逻辑不变)
class my_modal(discord.ui.Modal, title="反馈/建议"):
    # 这里添加你的Modal组件,比如输入框等
    pass

@client.event
async def on_ready():
    # 同步命令到全局(测试阶段可指定服务器ID快速生效)
    # await tree.sync(guild=discord.Object(id=你的服务器ID))
    await tree.sync()
    print(f"已登录为 {client.user}")

@tree.command(name="report", description="向机器人提交反馈或报告问题")
@app_commands.guild_only()
async def report(interaction: discord.Interaction):
    await interaction.response.send_modal(my_modal())

# 如果需要保留suggest作为斜杠命令别名,单独注册指向同一逻辑的命令
@tree.command(name="suggest", description="向机器人提交建议")
@app_commands.guild_only()
async def suggest(interaction: discord.Interaction):
    await report(interaction)

client.run("你的机器人令牌")

关键说明

  • 若你用的是commands.Bot而非discord.Client,直接用client.tree即可,无需单独初始化CommandTree。
  • 全局命令同步可能需要1小时左右生效,指定服务器ID的同步会立刻生效,适合测试场景。
  • 应用命令不要混用前缀命令的装饰器(如@commands.guild_only()),必须使用app_commands下的对应装饰器。

内容的提问来源于stack exchange,提问作者TheRealKurumi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 20:05:15