外观
Discord
Discord 官方机器人。Gateway WebSocket 连接 + REST 发送,支持文本 / 图片 / 视频 / 语音 / 文件,私聊自动解析 DM 频道。需海外环境并开启 Message Content Intent。
适配器类型:"discord" 源码:src/adapter/discord/ 协议:Discord Bot API v10(WebSocket 网关 + REST 发送)。
说明
特点
- Gateway WebSocket 接收事件,REST 发送消息
- 支持文本、图片、视频、文件
- 私聊自动解析 DM 频道(优先缓存,否则调用 API 创建)
- 机器人自己的消息自动忽略(防死循环)
原理
- 接收:Gateway WebSocket 连接,订阅 intents,Discord 推送事件
- 发送:
POST https://discord.com/api/v10/channels/{channel_id}/messages - 私聊:自动获取/创建 DM 频道后发送
前提
- Discord Developer Portal 创建应用并获取 Bot Token
- 必须开启 Message Content Intent(否则读不到消息正文)
- 运行环境能访问 discord.com(国内需海外服务器或代理)
- 机器人已加入目标服务器
安装
适配器安装
bash
van adapter install discord依赖库
bash
npm install ws配置
jsonc
{
"botId": "DC-Bot",
"type": "discord",
"token": "你的DiscordBotToken",
"intents": 37377,
"reconnectDelay": 5000
}| 配置项 | 必填 | 说明 |
|---|---|---|
token | ✅ | Discord 开发者平台 Bot Token |
intents | 可选 | 默认 37377(GUILDS + GUILD_MESSAGES + DIRECT_MESSAGES + MESSAGE_CONTENT) |
reconnectDelay | 可选 | 断线重连毫秒,默认 5000 |
默认 intents = 37377(GUILDS 1 + GUILD_MESSAGES 512 + DIRECT_MESSAGES 4096 + MESSAGE_CONTENT 32768)。自定义时必须包含 GUILD_MESSAGES(512) 和 DIRECT_MESSAGES(4096)。
intents 参考
| Intent | 值 | 说明 |
|---|---|---|
| GUILDS | 1 | 频道/服务器基础 |
| GUILD_MEMBERS | 2 | 成员变动(特权) |
| GUILD_MESSAGES | 512 | 频道消息 |
| GUILD_MESSAGE_REACTIONS | 1024 | 消息表态 |
| DIRECT_MESSAGES | 4096 | 私聊消息 |
| MESSAGE_CONTENT | 32768 | 读取消息正文(特权,必开) |
接收事件
| Discord 事件 | 框架事件 | 说明 |
|---|---|---|
MESSAGE_CREATE(有 guild_id) | group_message | 频道消息,groupId=channel_id |
MESSAGE_CREATE(无 guild_id) | private_message | 私聊消息 |
事件对象字段:
ts
{
botId: "DC-Bot",
selfId: "机器人id",
userId: "author.id",
groupId: "channel_id",
message: [{ type: "text", data: { text: "..." } }],
postType: "group_message" | "private_message",
raw: { ...原始消息, sender, message_id, time, platform: "discord" }
}API 调用
发送消息
ts
// 频道消息
await bot.callApi("send_group_msg", { group_id: "频道id", message: "大家好" })
// 私聊消息(自动解析 DM 频道)
await bot.callApi("send_private_msg", { user_id: "用户id", message: "你好" })
// 自动判断
await bot.callApi("send_msg", { group_id: "频道id", user_id: "用户id", message: "..." })消息段
- 文本 →
text段 - 图片 →
image段(data.url为公网 url,以 embed 方式附带) - markdown 段 → 以纯文本发送(Discord 消息本身支持部分 markdown 语法渲染)
常见问题
- 收不到消息:确认已开启 Message Content Intent、机器人已加入服务器、给了读取权限;私聊需用户先发消息。
- 401 Unauthorized:token 错误。
- 连不上网关:国内网络问题,需代理/海外环境。
- MESSAGE_CONTENT 报错:后台没开特权 intent,或订阅了无权限的 intent。
相关项目
- Discord Developer Portal:https://discord.com/developers/applications
- Gateway 文档:https://discord.com/developers/docs/events/gateway
