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

如何用Discord.py实现机器人向另一机器人发送斜杠命令?

问题:机器人发送斜杠命令无法被其他机器人识别

我开发了一款Discord机器人,需要在频道中发送斜杠命令给另一款机器人,但发送的/spoiler 'this is spoiler'被当成普通文本,对方机器人完全不识别这是命令。我的代码如下:

import discord
import asyncio

client = discord.Client()

@client.event
async def on_ready():
    print("Bot is ready.")

@client.event
async def on_message(message):
    async with message.channel.typing(): await asyncio.sleep(2)
    # Send a message after 5 seconds
    await message.channel.send("/spoiler 'this is spoiler'")
    return

client.run('My_Bot_Token')

我已经尝试了以下方法,均无效:

  • 使用typing()方法,无效果
  • 查阅Discord.py文档,未找到相关解决方法
  • 搜索网络,未找到机器人发送斜杠命令的相关内容

原因分析

Discord的斜杠命令(Slash Commands)不是通过发送普通文本消息触发的。你发送的/spoiler 'this is spoiler'只是一段带斜杠的文本,Discord不会将其解析为真正的斜杠命令请求,自然也不会路由到目标机器人。只有通过Discord官方API发送的交互请求(Interaction),才会被识别为斜杠命令触发。

解决方案

要触发另一款机器人的斜杠命令,你需要构造并发送符合Discord规范的交互请求。以下是具体实现步骤和代码示例:

1. 获取必要的ID信息

  • 目标机器人的ID(application_id):可在Discord开发者门户或服务器成员列表中找到目标机器人的ID
  • 目标斜杠命令的ID(command_id):通过调用Discord API获取,针对服务器内的命令,请求GET /guilds/{服务器ID}/commands;针对全局命令,请求GET /applications/{目标机器人ID}/commands

2. 修改代码发送交互请求

使用Discord.py的RestClient构造并发送交互请求:

import discord
import asyncio
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("Bot is ready.")

@bot.event
async def on_message(message):
    async with message.channel.typing():
        await asyncio.sleep(2)
    
    # 替换为实际的目标机器人ID和/spoiler命令ID
    target_app_id = 123456789012345678
    target_command_id = 987654321098765432
    
    # 构造交互请求数据,根据目标命令的参数结构调整options
    interaction_data = {
        "type": 2,  # 表示ApplicationCommand类型的交互
        "application_id": str(target_app_id),
        "guild_id": str(message.guild.id) if message.guild else None,
        "channel_id": str(message.channel.id),
        "session_id": "bot_session_123",  # 可自定义任意字符串
        "data": {
            "id": str(target_command_id),
            "name": "spoiler",
            "options": [
                {"name": "content", "value": "this is spoiler"}  # 替换为目标命令的参数名和值
            ]
        }
    }
    
    # 发送交互请求
    rest_client = discord.RestClient(token=bot.http.token)
    await rest_client.post("/interactions", json=interaction_data)
    
    await bot.process_commands(message)

bot.run('My_Bot_Token')

注意事项

  • 确保你的机器人拥有目标频道的发送消息权限
  • 不同斜杠命令的参数结构不同,需要根据目标命令的定义调整options字段
  • 如果目标命令是全局命令,不需要填写guild_id字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:46:12