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

如何在discord.py中编写分组应用(交互)命令

如何在discord.py中实现带分组子命令的/say交互命令

首先确保你使用的是discord.py 2.0+版本,交互命令是该版本新增的核心特性,先通过命令更新:
pip install -U discord.py

以下是完整实现代码,包含/say message和/say embed两个子命令:

import discord
from discord import app_commands
from discord.ext import commands

# 配置机器人意图,需开启消息内容权限
intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

@bot.event
async def on_ready():
    print(f"已登录为 {bot.user}")
    # 同步交互命令到Discord服务器
    try:
        synced_commands = await bot.tree.sync()
        print(f"已同步 {len(synced_commands)} 条命令")
    except Exception as e:
        print(f"命令同步失败: {e}")

# 创建/say主命令(作为子命令的分组容器)
@bot.tree.command(name="say", description="发送普通消息或嵌入格式消息")
async def say_group(interaction: discord.Interaction):
    # 主命令无需执行逻辑,用户调用时会自动显示子命令选项
    await interaction.response.send_message("请选择子命令:/say message 或 /say embed", ephemeral=True)

# 子命令:/say message 发送普通文本
@app_commands.describe(content="要发送的消息内容")
@say_group.subcommand(name="message", description="发送普通文本消息")
async def say_message(interaction: discord.Interaction, content: str):
    await interaction.channel.send(content)
    await interaction.response.send_message("消息已发送", ephemeral=True)

# 子命令:/say embed 发送嵌入消息
@app_commands.describe(title="嵌入消息标题", description="嵌入消息描述内容")
@say_group.subcommand(name="embed", description="发送带格式的嵌入消息")
async def say_embed(interaction: discord.Interaction, title: str, description: str):
    embed = discord.Embed(title=title, description=description, color=discord.Color.blue())
    await interaction.channel.send(embed=embed)
    await interaction.response.send_message("嵌入消息已发送", ephemeral=True)

# 替换为你的机器人令牌
bot.run("YOUR_BOT_TOKEN")

关键说明

  1. 主命令作为分组容器:/say本身不执行实际操作,仅作为子命令的入口,用户在Discord输入/say时会自动弹出子命令选项。
  2. 子命令绑定:通过@主命令对象.subcommand()装饰器,将子命令绑定到主命令分组下。
  3. 参数描述:app_commands.describe()用于给子命令的参数添加说明,用户在输入命令时会看到对应提示。
  4. 权限与同步:
    • 需在Discord开发者门户的Bot页面开启「Message Content Intent」权限。
    • 首次运行机器人会自动同步全局命令(可能需等待1-5分钟),若需快速同步到指定服务器,可在@bot.tree.command()中添加guild=discord.Object(id=你的服务器ID)参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 05:06:01