Discord 开发者平台调用手册

注册测试命令并处理签名回调

注册服务器内 /ping 命令,并运行一个仅用 Node.js 内置模块的签名验证回调服务。

官方资料核对 2026-10-15示例代码,未进行真实接口实测
← 返回平台功能

接入准备

  • 安装应用时包含 applications.commands;本例在自己的测试服务器执行。
  • 公网 HTTPS 地址可转发到本机 127.0.0.1:3000,保留原始请求体和签名请求头。
  • 从应用 General Information 取得 Application ID 和 Public Key;Public Key 用于验签,不是 Bot Token。

准备环境变量

示例值需要替换为自己的凭证或资源 ID。代码在本机或服务端运行;密钥不应放进公开网页。

DISCORD_BOT_TOKEN
Developer Portal → Bot 中生成的 Token;Authorization 前缀是 Bot,不是 Bearer。
DISCORD_APPLICATION_ID
应用的 Application ID。
DISCORD_GUILD_ID
测试服务器 ID,按字符串处理。
DISCORD_PUBLIC_KEY
General Information 中的 32 字节 Ed25519 公钥,64 位十六进制。
终端
export DISCORD_BOT_TOKEN='replace_with_bot_token'
export DISCORD_APPLICATION_ID='555555555555555555'
export DISCORD_GUILD_ID='666666666666666666'
export DISCORD_PUBLIC_KEY='replace_with_64_hex_public_key'

以上 export 适用于 macOS / Linux 的终端,在同一终端内运行后续代码。Python 示例保存为 request.py 后执行 python3 request.py。

调用步骤

  1. 01

    保存 DISCORD_APPLICATION_ID、DISCORD_GUILD_ID、DISCORD_BOT_TOKEN、DISCORD_PUBLIC_KEY。

  2. 02

    把 Node.js 回调代码保存为 interactions.mjs 后运行 node interactions.mjs,并配置 HTTPS 反向代理到 3000 端口。

  3. 03

    在应用 General Information 设置 Interactions Endpoint URL 为 https://你的域名/interactions,Discord 会发送 PING 验证;验签失败必须返回 401。

  4. 04

    执行注册命令操作;服务器命令立即可用,同名会覆盖已有命令定义。

  5. 05

    在测试服务器输入 /ping;服务会返回仅自己可见的 Pong。

调用 01

注册服务器斜杠命令

仅注册当前测试服务器的命令,不覆盖整套全局命令。

POSThttps://discord.com/api/v10/applications/${DISCORD_APPLICATION_ID}/guilds/${DISCORD_GUILD_ID}/commands

请求头

Authorization
Bot ${DISCORD_BOT_TOKEN}
Content-Type
application/json

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
application_id / guild_idPathsnowflake必填应用与测试服务器 ID。
name请求体string必填1–32 字符,CHAT_INPUT 名称遵循官方命名规则,本例 ping。
description请求体string必填CHAT_INPUT 命令说明,1–100 字符。
type请求体integer可选1 为 CHAT_INPUT(斜杠命令),默认 1。

调用代码

替换示例 ID 与请求体内容后运行。cURL 会报 HTTP 错误,业务状态还需按下方返回示例核对。

cURL
cat > request-body.json <<'JSON'
{
  "name": "ping",
  "description": "检查接口服务是否正常",
  "type": 1
}
JSON

# 执行后核对返回 JSON 的业务状态;HTTP 200 仍可能包含业务错误。
curl --silent --show-error --fail-with-body \
  --request POST \
  --url "https://discord.com/api/v10/applications/${DISCORD_APPLICATION_ID}/guilds/${DISCORD_GUILD_ID}/commands" \
  --header "Authorization: Bot ${DISCORD_BOT_TOKEN}" \
  --header "Content-Type: application/json" \
  --data-binary @request-body.json
Python 3
import json
import os
import re
import urllib.request
import urllib.error

def expand(value):
    return re.sub(r"\$\{([A-Z][A-Z0-9_]*)\}",
                  lambda match: os.environ[match.group(1)], value)

url = expand("https://discord.com/api/v10/applications/${DISCORD_APPLICATION_ID}/guilds/${DISCORD_GUILD_ID}/commands")
headers = {
    "Authorization": expand("Bot ${DISCORD_BOT_TOKEN}"),
    "Content-Type": expand("application/json"),
}
body = {
    "name": "ping",
    "description": "检查接口服务是否正常",
    "type": 1,
}
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
try:
    with urllib.request.urlopen(request, timeout=30) as response:
        result = json.load(response)
except urllib.error.HTTPError as error:
    print(f"HTTP {error.code}: {error.read().decode('utf-8', errors='replace')}")
    raise SystemExit(1)
print(json.dumps(result, ensure_ascii=False, indent=2))
Node.js
// Node.js 22+,保存为 request.mjs 后运行 node request.mjs
function expand(value) {
  return value.replace(/\$\{([A-Z][A-Z0-9_]*)\}/g, (_, name) => {
    if (!process.env[name]) throw new Error(`缺少环境变量 ${name}`);
    return process.env[name];
  });
}

const url = expand("https://discord.com/api/v10/applications/${DISCORD_APPLICATION_ID}/guilds/${DISCORD_GUILD_ID}/commands");
const headers = Object.fromEntries(
  Object.entries({
  "Authorization": "Bot ${DISCORD_BOT_TOKEN}",
  "Content-Type": "application/json"
}).map(([key, value]) => [key, expand(value)])
);
const body = {
  "name": "ping",
  "description": "检查接口服务是否正常",
  "type": 1
};
const response = await fetch(url, {
  method: "POST",
  headers,
  body: JSON.stringify(body),
  signal: AbortSignal.timeout(30000),
});
const text = await response.text();
if (!response.ok) throw new Error(`HTTP ${response.status}: ${text}`);
const result = JSON.parse(text);
console.log(JSON.stringify(result, null, 2));

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。新建 HTTP 201,同名更新 HTTP 200;均返回 Application Command。 以下为结构示意,非本站实测结果。

JSON
{
  "id": "777777777777777777",
  "application_id": "555555555555555555",
  "guild_id": "666666666666666666",
  "name": "ping",
  "description": "检查接口服务是否正常",
  "type": 1
}

常见错误与排查

HTTP 401凭证无效或认证格式错误
核对 Bot Token 与 Bot 前缀,或 Webhook ID/Token。
HTTP 403权限不足
检查服务器安装权限及频道覆盖规则。
HTTP 404资源不存在或不可访问
核对 ID 和机器人可见范围,不要反复请求已删除资源。
HTTP 429请求限流
按 retry_after 或 Retry-After 等待,并遵守响应中的 rate limit bucket。

调用注意

  • 同名命令会更新之前的定义;不要把测试名称与现有业务命令重名。
调用 02

接收交互并验证 Ed25519 签名

这是你托管的接收端,Discord 主动 POST 到这里;自定义 Node.js 示例运行服务器,不能用通用 HTTP 客户端代码替代。

你的 HTTPS 回调接收地址,以下域名为示例。

POSThttps://example.com/interactions

参数说明

参数表可左右滑动,查看完整说明。

字段 / 位置类型 / 必填说明
X-Signature-Ed25519Headerhex string必填Discord 提供的请求签名,必须验签。
X-Signature-TimestampHeaderstring必填签名时间戳;以原始文本字节拼接原始 HTTP body 验签,不能 JSON 解析重序列化后验证。
type请求体integer必填1 为 PING 验证;2 为应用命令。
data.name请求体string可选type=2 的应用命令请求中必填,本例只处理 ping;PING(type=1)不含此字段。

调用代码

这是接收平台回调的服务端示例,运行前完成上方 HTTPS 转发与环境变量配置。

Node.js
// 保存为 interactions.mjs,Node.js 22 直接运行;由 HTTPS 反向代理转发到本机 3000。
import http from "node:http";
import { createPublicKey, verify } from "node:crypto";
const hex = process.env.DISCORD_PUBLIC_KEY;
if (!/^[0-9a-f]{64}$/i.test(hex ?? "")) throw new Error("DISCORD_PUBLIC_KEY 必须是后台的 64 位十六进制公钥");
const key = createPublicKey({ key: Buffer.from("302a300506032b6570032100" + hex, "hex"), format: "der", type: "spki" });
http.createServer(async (req, res) => {
  const reply = (status, body) => { res.writeHead(status, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); };
  if (req.method !== "POST" || req.url !== "/interactions") return reply(404, { error: "not_found" });
  try {
    const chunks = []; let size = 0;
    for await (const chunk of req) { size += chunk.length; if (size > 1048576) return reply(413, { error: "too_large" }); chunks.push(chunk); }
    const raw = Buffer.concat(chunks);
    const sig = req.headers["x-signature-ed25519"];
    const ts = req.headers["x-signature-timestamp"];
    if (typeof sig !== "string" || !/^[0-9a-f]{128}$/i.test(sig) || typeof ts !== "string" || !/^\d+$/.test(ts)) return reply(401, { error: "invalid_signature" });
    const signed = Buffer.concat([Buffer.from(ts), raw]);
    if (!verify(null, signed, key, Buffer.from(sig, "hex"))) return reply(401, { error: "invalid_signature" });
    // 独立的新鲜度窗口,降低重放风险。服务器需校准时钟。
    if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return reply(401, { error: "stale_request" });
    const event = JSON.parse(raw.toString("utf8"));
    if (event.type === 1) return reply(200, { type: 1 });
    if (event.type === 2 && event.data?.name === "ping") return reply(200, { type: 4, data: { content: "Pong,接口服务正常。", flags: 64, allowed_mentions: { parse: [] } } });
    return reply(400, { error: "unsupported_interaction" });
  } catch { return reply(400, { error: "invalid_request" }); }
}).listen(3000, "127.0.0.1", () => console.log("Interactions listening on 127.0.0.1:3000"));

返回示例

按官方字段整理的节选示意,使用虚构 ID,不是实测结果。HTTP 200 返回交互响应,flags=64 表示仅调用者可见;PING 则响应 {type:1}。 以下为结构示意,非本站实测结果。

JSON
{
  "type": 4,
  "data": {
    "content": "Pong,接口服务正常。",
    "flags": 64,
    "allowed_mentions": {
      "parse": []
    }
  }
}

常见错误与排查

HTTP 401(由你的服务返回)请求签名无效
检查公钥、原始 body 是否被代理改写,并拒绝无效签名。
3 秒内未初次响应交互令牌失效
耗时业务先回复 type=5 延后响应,再在有效期内补结果。

调用注意

  • 初次响应必须在 3 秒内;交互 Token 通常可用于 15 分钟内的后续消息。
  • 本例只做只读 ping;加入业务写操作后还需校验用户/服务器权限,并按 interaction id 去重。
  • 生产环境补进程管理、监控、TLS 代理与容量控制;页面示例未部署或实测。

注意事项

  • Interaction 通过 Gateway 或 HTTP Webhook 二选一;这里选择 HTTP 回调。

核验来源

本站按官方资料整理本场景的必要调用步骤与代码,覆盖范围以本页列出的接口为准。官方资料用于追溯规范及查看变更。

  1. 01
    Building your first Discord Bot核验日期 2026-10-15
  2. 02
    Application Commands核验日期 2026-10-15
  3. 03

Discord 开发者平台的其他调用手册

← 返回Discord 开发者平台的全部功能