@zhin.js/adapter-discord 5.0.1 → 5.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +51 -76
  3. package/adapters/discord.ts +46 -0
  4. package/agent/tools/add_role.ts +24 -0
  5. package/agent/tools/create_thread.ts +25 -0
  6. package/agent/tools/forum_post.ts +24 -0
  7. package/agent/tools/list_roles.ts +22 -0
  8. package/agent/tools/react.ts +22 -0
  9. package/agent/tools/remove_role.ts +24 -0
  10. package/agent/tools/send_embed.ts +37 -0
  11. package/lib/discord-agent-deps.d.ts +35 -0
  12. package/lib/discord-agent-deps.js +32 -0
  13. package/lib/endpoint.d.ts +66 -119
  14. package/lib/endpoint.js +308 -1047
  15. package/lib/gateway.d.ts +122 -0
  16. package/lib/gateway.js +235 -0
  17. package/lib/index.d.ts +6 -18
  18. package/lib/index.js +6 -330
  19. package/lib/platform-permit.d.ts +1 -2
  20. package/lib/platform-permit.js +4 -2
  21. package/lib/protocol.d.ts +135 -0
  22. package/lib/protocol.js +234 -0
  23. package/lib/webhook.d.ts +13 -0
  24. package/lib/webhook.js +86 -0
  25. package/package.json +48 -31
  26. package/plugin.ts +13 -0
  27. package/schema.json +63 -0
  28. package/src/discord-agent-deps.ts +79 -0
  29. package/src/endpoint.ts +385 -1167
  30. package/src/gateway.ts +337 -0
  31. package/src/index.ts +55 -332
  32. package/src/platform-permit.ts +1 -2
  33. package/src/protocol.ts +392 -0
  34. package/src/webhook.ts +121 -0
  35. package/client/Dashboard.tsx +0 -195
  36. package/client/index.tsx +0 -11
  37. package/client/tsconfig.json +0 -7
  38. package/client/utils/api.ts +0 -30
  39. package/dist/index.js +0 -29
  40. package/lib/adapter.d.ts +0 -25
  41. package/lib/adapter.d.ts.map +0 -1
  42. package/lib/adapter.js +0 -96
  43. package/lib/adapter.js.map +0 -1
  44. package/lib/endpoint-interactions.d.ts +0 -34
  45. package/lib/endpoint-interactions.d.ts.map +0 -1
  46. package/lib/endpoint-interactions.js +0 -284
  47. package/lib/endpoint-interactions.js.map +0 -1
  48. package/lib/endpoint.d.ts.map +0 -1
  49. package/lib/endpoint.js.map +0 -1
  50. package/lib/index.d.ts.map +0 -1
  51. package/lib/index.js.map +0 -1
  52. package/lib/platform-permit.d.ts.map +0 -1
  53. package/lib/platform-permit.js.map +0 -1
  54. package/lib/segment-mapper.d.ts +0 -2
  55. package/lib/segment-mapper.d.ts.map +0 -1
  56. package/lib/segment-mapper.js +0 -2
  57. package/lib/segment-mapper.js.map +0 -1
  58. package/lib/types.d.ts +0 -49
  59. package/lib/types.d.ts.map +0 -1
  60. package/lib/types.js +0 -2
  61. package/lib/types.js.map +0 -1
  62. package/plugin.yml +0 -3
  63. package/src/adapter.ts +0 -108
  64. package/src/endpoint-interactions.ts +0 -354
  65. package/src/segment-mapper.ts +0 -1
  66. package/src/types.ts +0 -60
  67. /package/{skills/discord → agent}/PERMITS.md +0 -0
  68. /package/{skills/discord/SKILL.md → agent/skills/discord.md} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,60 @@
1
1
  # @zhin.js/adapter-discord
2
2
 
3
+ ## 5.0.3
4
+
5
+ ### Patch Changes
6
+
7
+ - cc5c94d: 约定式插件运行时迁移(breaking):插件与适配器由 `usePlugin()` / `extends Adapter` 迁移为 `definePlugin` / `defineAdapter` + `plugin.ts` + 约定目录(`adapters/`、`commands/`、`components/`、`tools/` 等)。
8
+
9
+ - 新增约定式运行时包:`@zhin.js/plugin-runtime`、`@zhin.js/adapter`、`@zhin.js/runtime`、`@zhin.js/host-http`(首版 1.0.0 走 init-publish,不在本 changeset 内 bump)。
10
+ - 全部 20 个平台适配器改为约定式 `defineAdapter`,旧 `usePlugin` / `extends Adapter` / `segment-mapper` 生产入口已删除;onebot11 反向 WSS、onebot12 webhook/wss、milky sse/webhook/wss、satori webhook、kook webhook、qq webhook/middleware 等 slice 1 推迟的连接模式已补齐。
11
+ - 游戏 / 工具 / 服务插件同步迁移到约定目录结构。
12
+ - CLI 增加 plugin-runtime host installer(http/database/outbound/schedule/console 等)。
13
+
14
+ 后续加固(同批):
15
+
16
+ - CLI:`zhin runtime start --daemon`(pidfile/崩溃拉起/风暴保护),orphan watchdog 防僵尸进程;legacy `zhin dev` / `zhin start` 已移除(含 `zhin restart`),`zhin stop` 兼容新 daemon。
17
+ - 安全:builtin 工具统一走 `security/policy-facade.ts` 的 `runToolPolicies`(声明式策略表,deny 优先);审计日志 close flush + 背压队列;`splitCompoundCommand` 引号感知、`extractCommandName` 去引号堵绕过。
18
+ - 日志:Logger 双堆栈修复、本地时区、`getLogger` 挂树(`setLevel` 递归生效)、第三方库(log4js/discord)桥接、启动人读总结。
19
+ - 结构:`plugins/games/shared` 迁为 `packages/game-kit`(`@zhin.js/game-kit`);死目录 `plugins/adapters/common` 删除。
20
+ - 脚手架:`create-zhin-app` / `zhin new` / scaffold-wizard 生成物改为 Plugin Runtime 形态(minimal-bot 同构,新配置格式)。
21
+ - Console:endpoint.list 真实名称与 phase、schema:get-all 按 instanceKey 映射、db:\* 接 DatabaseHost。
22
+
23
+ 注:按仓库发布惯例(见 1bb345dd2),本次 breaking 迁移统一使用 patch,避免 zhin.js 5.0 级联。
24
+
25
+ - 447f3e2: 迁移缺口修复(legacy 功能对齐):
26
+
27
+ - html 段出站规范化:经 `@zhin.js/html-renderer` 渲染为 image 段(sandbox 豁免、无渲染器时降级文本),修复真实平台 `[object Object]`。
28
+ - 群聊 @ 触发 AI:适配器入站标注 `metadata.mentioned`(icqq/qq/slack/onebot11/onebot12/napcat/milky/discord/telegram/kook/dingtalk/satori),`matchAiTrigger` 补齐 ignorePrefixes/respondToAt/respondToPrivate/keywords(默认值与 legacy 对齐)。
29
+ - im_transcripts 全量流水恢复写入(chat_history 工具可用);群聊旁听上下文回迁。
30
+ - `ai.trigger.timeout/thinkingMessage/errorTemplate` 生效;masters/trusted 角色解析对齐 legacy。
31
+ - `Message.sender` 统一为用户 ID(onebot11/12、napcat、milky 原误传显示名);quote_id 经 metadata 接入 AI 引用上下文。
32
+
33
+ - Updated dependencies [16ec4e8]
34
+ - Updated dependencies [cc5c94d]
35
+ - Updated dependencies [447f3e2]
36
+ - @zhin.js/core@1.3.5
37
+ - @zhin.js/agent@1.0.4
38
+ - @zhin.js/host-http@1.0.1
39
+ - zhin.js@4.1.3
40
+ - @zhin.js/logger@1.0.75
41
+ - @zhin.js/plugin-runtime@1.0.1
42
+ - @zhin.js/adapter@1.0.1
43
+
44
+ ## 5.0.2
45
+
46
+ ### Patch Changes
47
+
48
+ - 872c583: fix: 代码格式优化
49
+ - Updated dependencies [872c583]
50
+ - Updated dependencies [872c583]
51
+ - @zhin.js/agent@1.0.3
52
+ - @zhin.js/client@2.0.5
53
+ - @zhin.js/contract@1.0.3
54
+ - @zhin.js/host-api@2.0.5
55
+ - @zhin.js/host-router@2.0.3
56
+ - zhin.js@4.1.2
57
+
3
58
  ## 5.0.1
4
59
 
5
60
  ### Patch Changes
package/README.md CHANGED
@@ -1,15 +1,15 @@
1
1
  # @zhin.js/adapter-discord
2
2
 
3
- Zhin.js Discord 适配器,支持 Discord 机器人的消息收发和服务器管理。
3
+ Zhin.js Discord 适配器(Plugin Runtime),默认通过 **Gateway WebSocket**(discord.js)收发消息(无需 host-router / host-http)。
4
4
 
5
- ## 功能特性
5
+ ## 功能
6
6
 
7
- - 📦 **单一适配器**:`context: discord`,通过 `connection` 选择连接方式
8
- - 🌐 **Gateway**(`connection: gateway`):WebSocket 网关,支持群管、消息、斜杠命令等
9
- - 📮 **Interactions**(`connection: interactions`):HTTP 交互端点,斜杠命令等
10
- - 可配置 Intents 和默认活动状态
11
- - 服务器管理 AI 工具(仅 Gateway 支持)
12
- - 基于 discord.js
7
+ - Gateway WebSocket 入站(默认;无需公网 HTTPS / host)
8
+ - 解析 text / mention / attachment / embed / sticker / button
9
+ - 支持私聊、群组与服务器频道
10
+ - 出站 `send({ target, payload })` → Discord channel message(text / media / embed / keyboard)
11
+ - 约定式 `defineAdapter` / `definePlugin`(无需 `usePlugin`)
12
+ - Interactions HTTP webhook 延期(需 `httpHostToken`);配置 `connection: interactions` 会明确报错
13
13
 
14
14
  ## 安装
15
15
 
@@ -17,98 +17,73 @@ Zhin.js Discord 适配器,支持 Discord 机器人的消息收发和服务器
17
17
  pnpm add @zhin.js/adapter-discord discord.js
18
18
  ```
19
19
 
20
- Interactions 模式需同时启用 `@zhin.js/host-router`。
20
+ ## Plugin Runtime
21
21
 
22
- ## 配置
22
+ - `@zhin.js/adapter` — 约定式 `adapters/discord.ts`(`defineAdapter`)
23
+ - `@zhin.js/core` — `messageGatewayToken` 入站/出站
24
+ - `@zhin.js/plugin-runtime` — `plugin.ts`(`definePlugin`)
25
+ - 配置经插件 `schema.json` 落到 `plugins.<instanceKey>`
26
+ - **无需** `@zhin.js/host-http` / `@zhin.js/host-router`(Gateway 路径)
23
27
 
24
- 所有 Endpoint 使用 **同一 context:`discord`**,通过 **`connection`** 区分连接方式。
28
+ 入站:`gateway.receive({ adapter, target: channelId, content: text, sender, metadata })`
29
+ 出站:`send({ target, payload })` → discord.js channel.send
25
30
 
26
- ### Gateway(connection: gateway,默认)
31
+ ### 平台权限(platform permit)
27
32
 
28
- ```yaml
29
- plugins:
30
- - "@zhin.js/adapter-discord"
33
+ - sender role 已恢复:Gateway 入站 `metadata.role` / `metadata.permissions`(来自 member 权限位与 guild owner 判定,见 `src/gateway.ts` `resolveSenderRole`)。
34
+ - `plugin.ts` 在 generation setup 注册 checker,并在 dispose 注销;Plugin Runtime CapabilityIngress 与 ToolSystem 统一经 Core `canAccessTool()` 消费 `permissions`。
31
35
 
32
- endpoints:
33
- - context: discord
34
- connection: gateway
35
- name: my-discord-bot
36
- token: "${DISCORD_BOT_TOKEN}"
37
- # 可选: intents, enableSlashCommands, defaultActivity, slashCommands
38
- ```
36
+ ## 前置条件
37
+
38
+ | 要求 | 说明 |
39
+ |------|------|
40
+ | **Bot Token** | [Discord Developer Portal](https://discord.com/developers/applications) 创建应用并获取 Token |
41
+ | **MESSAGE CONTENT INTENT** | 需开启才能读取消息正文 |
42
+ | **Gateway(默认)** | 本地/生产均可;discord.js 连接 Gateway,无需公网 HTTPS |
43
+ | **host-http** | Gateway **不需要**;Interactions webhook 延期至下一棒 |
39
44
 
40
- ### Interactions(connection: interactions)
45
+ 必填字段:`token`。
46
+
47
+ ## 最小配置
41
48
 
42
49
  ```yaml
50
+ # zhin.config.yml(Plugin Runtime)
43
51
  plugins:
44
- - "@zhin.js/host-router"
45
- - "@zhin.js/adapter-discord"
46
-
47
- endpoints:
48
- - context: discord
49
- connection: interactions
52
+ discord:
50
53
  name: my-discord-bot
51
- token: "${DISCORD_BOT_TOKEN}"
52
- applicationId: "${DISCORD_APP_ID}"
53
- publicKey: "${DISCORD_PUBLIC_KEY}"
54
- interactionsPath: "/discord/interactions"
54
+ token: ${DISCORD_BOT_TOKEN}
55
+ # connection: gateway # 默认
55
56
  ```
56
57
 
57
- 未写 `connection` 时默认为 `gateway`。
58
-
59
- ### 如何选择 connection
60
-
61
- | 模式 | 适用场景 | 依赖 |
62
- |------|----------|------|
63
- | **gateway** | 常规 Bot:读消息、群管、Gateway 事件 | Endpoint Token + Intents |
64
- | **interactions** | 仅需斜杠命令 / 交互组件,或 Gateway 与 HTTP 并存 | `@zhin.js/host-router` + Application ID + Public Key |
58
+ 根插件 `zhin.plugins`(或项目图)需引用 `@zhin.js/adapter-discord`(`instanceKey: discord`)。
65
59
 
66
- Gateway 需开启 **MESSAGE CONTENT INTENT**;Interactions 须在 Developer Portal 配置 **Interactions Endpoint URL**(指向 `interactionsPath`)。
60
+ ## 环境变量
67
61
 
68
- ## 使用示例
62
+ | 变量 | 说明 |
63
+ |------|------|
64
+ | `DISCORD_BOT_TOKEN` | Bot Token |
65
+ | `DISCORD_BOT_NAME` | 可选,默认 endpoint 名 |
69
66
 
70
- ### 注册命令
67
+ ## Interactions(HTTP)
71
68
 
72
- ```typescript
73
- import { usePlugin, MessageCommand } from 'zhin.js'
74
-
75
- const { addCommand } = usePlugin()
76
-
77
- addCommand(
78
- new MessageCommand('ping')
79
- .desc('测试延迟')
80
- .action(() => 'Pong!')
81
- )
82
- ```
83
-
84
- ### 消息中间件
85
-
86
- ```typescript
87
- import { usePlugin } from 'zhin.js'
88
-
89
- const { root } = usePlugin()
90
-
91
- root.addMiddleware(async (message, next) => {
92
- if (message.$adapter === 'discord') {
93
- console.log('Discord 消息:', message.$content)
94
- }
95
- await next()
96
- })
97
- ```
69
+ `connection: interactions` 经 `httpHostToken` 注册 POST 路由(默认 `/discord/interactions`),Ed25519 验签后处理 PING 与 slash command;出站走 Discord REST `channels/.../messages`。需配置 `applicationId` 与 `publicKey`。
98
70
 
99
71
  ## AI 工具(Skill)
100
72
 
101
- 适配器内置 Discord 服务器管理 Skill,工具供 AI 调用。
73
+ | 类别 | 路径 |
74
+ |------|------|
75
+ | Permit 词汇 | `agent/PERMITS.md` |
76
+ | 平台工具(7 个) | `agent/tools/`(`discord_*`:角色、Embed、反应等) |
77
+ | 技能说明 | `agent/skills/discord.md` |
102
78
 
103
- > 工具使用 Discord Snowflake ID 格式标识 `guild_id`、`user_id`、`channel_id`。
79
+ 工具使用 Discord Snowflake ID 标识 `guild_id`、`user_id`、`channel_id`。
104
80
 
105
81
  ## Discord 开发者配置
106
82
 
107
83
  1. 前往 [Discord Developer Portal](https://discord.com/developers/applications)
108
- 2. 创建应用并获取 Endpoint Token
109
- 3. 开启 **MESSAGE CONTENT INTENT**(需要读取消息内容)
110
- 4. 通过 OAuth2 URL 邀请 Endpoint 加入服务器
111
- 5. Interactions 模式还需配置 Interactions Endpoint URL
84
+ 2. 创建应用并获取 Bot Token
85
+ 3. 开启 **MESSAGE CONTENT INTENT**
86
+ 4. 通过 OAuth2 URL 邀请 Bot 加入服务器
112
87
 
113
88
  ## 许可证
114
89
 
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Convention entry: discover `adapters/discord.ts` → defineAdapter.
3
+ */
4
+ import { defineAdapter } from '@zhin.js/adapter';
5
+ import { messageGatewayToken } from '@zhin.js/core/runtime';
6
+ import { httpHostToken } from '@zhin.js/host-http';
7
+ import {
8
+ DiscordGatewayEndpoint,
9
+ DiscordInteractionsEndpoint,
10
+ } from '../src/endpoint.js';
11
+ import {
12
+ resolveDiscordConfig,
13
+ type DiscordAdapterConfig,
14
+ } from '../src/protocol.js';
15
+
16
+ export {
17
+ DiscordGatewayEndpoint,
18
+ DiscordInteractionsEndpoint,
19
+ } from '../src/endpoint.js';
20
+ export type {
21
+ CreateDiscordClient,
22
+ DiscordClientTransport,
23
+ DiscordEndpointOptions,
24
+ DiscordInteractionsEndpointOptions,
25
+ } from '../src/endpoint.js';
26
+
27
+ export default defineAdapter<DiscordAdapterConfig>({
28
+ capabilities: ['inbound', 'outbound'],
29
+ create(context) {
30
+ const config = resolveDiscordConfig(context.config);
31
+ const gateway = context.use(messageGatewayToken);
32
+ if (config.connection === 'interactions') {
33
+ return new DiscordInteractionsEndpoint({
34
+ id: context.id,
35
+ gateway,
36
+ http: context.use(httpHostToken),
37
+ config,
38
+ });
39
+ }
40
+ return new DiscordGatewayEndpoint({
41
+ id: context.id,
42
+ gateway,
43
+ config,
44
+ });
45
+ },
46
+ });
@@ -0,0 +1,24 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { platformPermit } from '../../src/platform-permit.js';
4
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
5
+
6
+ export default defineAgentTool<{ endpoint_id: string; guild_id: string; user_id: string; role_id: string }>({
7
+ description: '给成员添加 Discord 角色',
8
+ inputSchema: z.object({
9
+ endpoint_id: z.string().describe('Endpoint 名称'),
10
+ guild_id: z.string().describe('服务器 ID'),
11
+ user_id: z.string().describe('用户 ID'),
12
+ role_id: z.string().describe('角色 ID'),
13
+ }),
14
+ platforms: ['discord'],
15
+ tags: ['discord'],
16
+ permissions: [platformPermit('manage_roles')],
17
+ async execute({ endpoint_id, guild_id, user_id, role_id }: { endpoint_id: string; guild_id: string; user_id: string; role_id: string }) {
18
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
19
+ addRole: (guildId: string, userId: string, roleId: string) => Promise<boolean>;
20
+ };
21
+ const success = await endpoint.addRole(guild_id, user_id, role_id);
22
+ return { success, message: success ? `已给用户 ${user_id} 添加角色` : '操作失败' };
23
+ },
24
+ });
@@ -0,0 +1,25 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { platformPermit } from '../../src/platform-permit.js';
4
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
5
+
6
+ export default defineAgentTool<{ endpoint_id: string; channel_id: string; name: string; message_id?: string; auto_archive_duration?: number }>({
7
+ description: '在 Discord 频道中创建帖子/子线程',
8
+ inputSchema: z.object({
9
+ endpoint_id: z.string().describe('Endpoint 名称'),
10
+ channel_id: z.string().describe('频道 ID'),
11
+ name: z.string().describe('帖子标题'),
12
+ message_id: z.string().optional().describe('基于某条消息创建(可选)'),
13
+ auto_archive_duration: z.number().optional().describe('自动归档时间(分钟:60/1440/4320/10080)'),
14
+ }),
15
+ platforms: ['discord'],
16
+ tags: ['discord'],
17
+ permissions: [platformPermit('manage_channels')],
18
+ async execute({ endpoint_id, channel_id, name, message_id, auto_archive_duration }: { endpoint_id: string; channel_id: string; name: string; message_id?: string; auto_archive_duration?: number }) {
19
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
20
+ createThread: (channelId: string, threadName: string, messageId?: string, autoArchiveDuration?: number) => Promise<{ id: string }>;
21
+ };
22
+ const thread = await endpoint.createThread(channel_id, name, message_id, auto_archive_duration);
23
+ return { success: true, thread_id: thread.id, message: `帖子 "${name}" 已创建` };
24
+ },
25
+ });
@@ -0,0 +1,24 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
4
+
5
+ export default defineAgentTool<{ endpoint_id: string; channel_id: string; name: string; content: string; tags?: string }>({
6
+ description: '在 Discord 论坛频道中创建帖子',
7
+ inputSchema: z.object({
8
+ endpoint_id: z.string().describe('Endpoint 名称'),
9
+ channel_id: z.string().describe('论坛频道 ID'),
10
+ name: z.string().describe('帖子标题'),
11
+ content: z.string().describe('帖子内容'),
12
+ tags: z.string().optional().describe('标签名,逗号分隔(可选)'),
13
+ }),
14
+ platforms: ['discord'],
15
+ tags: ['discord'],
16
+ async execute({ endpoint_id, channel_id, name, content, tags }: { endpoint_id: string; channel_id: string; name: string; content: string; tags?: string }) {
17
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
18
+ createForumPost: (channelId: string, title: string, body: string, tagNames?: string[]) => Promise<{ id: string }>;
19
+ };
20
+ const tagList = tags ? tags.split(',').map((t: string) => t.trim()) : undefined;
21
+ const thread = await endpoint.createForumPost(channel_id, name, content, tagList);
22
+ return { success: true, thread_id: thread.id, message: `论坛帖 "${name}" 已创建` };
23
+ },
24
+ });
@@ -0,0 +1,22 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { platformPermit } from '../../src/platform-permit.js';
4
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
5
+
6
+ export default defineAgentTool<{ endpoint_id: string; guild_id: string }>({
7
+ description: '获取 Discord 服务器角色列表',
8
+ inputSchema: z.object({
9
+ endpoint_id: z.string().describe('Endpoint 名称'),
10
+ guild_id: z.string().describe('服务器 ID'),
11
+ }),
12
+ platforms: ['discord'],
13
+ tags: ['discord'],
14
+ permissions: [platformPermit('manage_roles')],
15
+ async execute({ endpoint_id, guild_id }: { endpoint_id: string; guild_id: string }) {
16
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
17
+ getRoles: (guildId: string) => Promise<unknown[]>;
18
+ };
19
+ const roles = await endpoint.getRoles(guild_id);
20
+ return { roles, count: roles.length };
21
+ },
22
+ });
@@ -0,0 +1,22 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
4
+
5
+ export default defineAgentTool<{ endpoint_id: string; channel_id: string; message_id: string; emoji: string }>({
6
+ description: '对 Discord 消息添加表情反应',
7
+ inputSchema: z.object({
8
+ endpoint_id: z.string().describe('Endpoint 名称'),
9
+ channel_id: z.string().describe('频道 ID'),
10
+ message_id: z.string().describe('消息 ID'),
11
+ emoji: z.string().describe('表情(Unicode 表情或自定义表情如 <:name:id>)'),
12
+ }),
13
+ platforms: ['discord'],
14
+ tags: ['discord'],
15
+ async execute({ endpoint_id, channel_id, message_id, emoji }: { endpoint_id: string; channel_id: string; message_id: string; emoji: string }) {
16
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
17
+ addReaction: (channelId: string, messageId: string, reaction: string) => Promise<void>;
18
+ };
19
+ await endpoint.addReaction(channel_id, message_id, emoji);
20
+ return { success: true, message: `已添加反应 ${emoji}` };
21
+ },
22
+ });
@@ -0,0 +1,24 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { platformPermit } from '../../src/platform-permit.js';
4
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
5
+
6
+ export default defineAgentTool<{ endpoint_id: string; guild_id: string; user_id: string; role_id: string }>({
7
+ description: '移除成员的 Discord 角色',
8
+ inputSchema: z.object({
9
+ endpoint_id: z.string().describe('Endpoint 名称'),
10
+ guild_id: z.string().describe('服务器 ID'),
11
+ user_id: z.string().describe('用户 ID'),
12
+ role_id: z.string().describe('角色 ID'),
13
+ }),
14
+ platforms: ['discord'],
15
+ tags: ['discord'],
16
+ permissions: [platformPermit('manage_roles')],
17
+ async execute({ endpoint_id, guild_id, user_id, role_id }: { endpoint_id: string; guild_id: string; user_id: string; role_id: string }) {
18
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
19
+ removeRole: (guildId: string, userId: string, roleId: string) => Promise<boolean>;
20
+ };
21
+ const success = await endpoint.removeRole(guild_id, user_id, role_id);
22
+ return { success, message: success ? `已移除用户 ${user_id} 的角色` : '操作失败' };
23
+ },
24
+ });
@@ -0,0 +1,37 @@
1
+ import { defineAgentTool } from '@zhin.js/agent/tools';
2
+ import { z } from 'zod';
3
+ import { getDiscordAgentDeps } from '../../src/discord-agent-deps.js';
4
+
5
+ export default defineAgentTool<{ endpoint_id: string; channel_id: string; title?: string; description?: string; color?: number; url?: string; fields?: string }>({
6
+ description: '发送 Discord 富文本嵌入消息(Embed)',
7
+ inputSchema: z.object({
8
+ endpoint_id: z.string().describe('Endpoint 名称'),
9
+ channel_id: z.string().describe('频道 ID'),
10
+ title: z.string().optional().describe('Embed 标题'),
11
+ description: z.string().optional().describe('Embed 描述'),
12
+ color: z.number().optional().describe('颜色值(十进制,如 0x00ff00 = 65280)'),
13
+ url: z.string().optional().describe('标题链接(可选)'),
14
+ fields: z.string().optional().describe('字段,JSON 格式: [{"name":"k","value":"v","inline":false}]'),
15
+ }),
16
+ platforms: ['discord'],
17
+ tags: ['discord'],
18
+ async execute({ endpoint_id, channel_id, title, description, color, url, fields }: { endpoint_id: string; channel_id: string; title?: string; description?: string; color?: number; url?: string; fields?: string }) {
19
+ const endpoint = getDiscordAgentDeps().getGatewayEndpoint(endpoint_id) as {
20
+ sendEmbed: (channelId: string, embed: Record<string, unknown>) => Promise<{ id: string }>;
21
+ };
22
+ const embedData: Record<string, unknown> = {};
23
+ if (title) embedData.title = title;
24
+ if (description) embedData.description = description;
25
+ if (color) embedData.color = color;
26
+ if (url) embedData.url = url;
27
+ if (fields) {
28
+ try {
29
+ embedData.fields = JSON.parse(fields);
30
+ } catch {
31
+ return { success: false, message: 'fields 格式错误,应为 JSON 数组' };
32
+ }
33
+ }
34
+ const msg = await endpoint.sendEmbed(channel_id, embedData);
35
+ return { success: true, message_id: msg.id, message: 'Embed 已发送' };
36
+ },
37
+ });
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Agent tool deps for discord.
3
+ * Endpoints register themselves on start; tools look up by config name / endpoint id.
4
+ */
5
+ export interface DiscordAgentEndpoint {
6
+ addRole(guildId: string, userId: string, roleId: string): Promise<boolean>;
7
+ removeRole(guildId: string, userId: string, roleId: string): Promise<boolean>;
8
+ getRoles(guildId: string): Promise<unknown[]>;
9
+ createThread(channelId: string, name: string, messageId?: string, autoArchiveDuration?: number): Promise<{
10
+ id: string;
11
+ }>;
12
+ addReaction(channelId: string, messageId: string, emoji: string): Promise<void>;
13
+ sendEmbed(channelId: string, embedData: Record<string, unknown>): Promise<{
14
+ id: string;
15
+ }>;
16
+ createForumPost(channelId: string, name: string, content: string, tags?: string[]): Promise<{
17
+ id: string;
18
+ }>;
19
+ kickMember(guildId: string, userId: string, reason?: string): Promise<boolean>;
20
+ banMember(guildId: string, userId: string, reason?: string): Promise<boolean>;
21
+ unbanMember(guildId: string, userId: string, reason?: string): Promise<boolean>;
22
+ timeoutMember(guildId: string, userId: string, duration?: number, reason?: string): Promise<boolean>;
23
+ setNickname(guildId: string, userId: string, nickname: string): Promise<boolean>;
24
+ getMembers(guildId: string, limit?: number): Promise<unknown[]>;
25
+ getGuildInfo(guildId: string): Promise<unknown>;
26
+ }
27
+ export interface DiscordAgentDeps {
28
+ getEndpoint: (endpointId: string) => DiscordAgentEndpoint;
29
+ /** Alias kept for existing agent/tools that call getGatewayEndpoint. */
30
+ getGatewayEndpoint: (endpointId: string) => DiscordAgentEndpoint;
31
+ }
32
+ export declare function registerDiscordAgentEndpoint(endpointId: string, endpoint: DiscordAgentEndpoint): () => void;
33
+ /** Optional override used by tests / transitional callers. Pass `null` to clear. */
34
+ export declare function setDiscordAgentDeps(deps: DiscordAgentDeps | null): void;
35
+ export declare function getDiscordAgentDeps(): DiscordAgentDeps;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Agent tool deps for discord.
3
+ * Endpoints register themselves on start; tools look up by config name / endpoint id.
4
+ */
5
+ const endpoints = new Map();
6
+ let override = null;
7
+ export function registerDiscordAgentEndpoint(endpointId, endpoint) {
8
+ endpoints.set(endpointId, endpoint);
9
+ return () => {
10
+ if (endpoints.get(endpointId) === endpoint) {
11
+ endpoints.delete(endpointId);
12
+ }
13
+ };
14
+ }
15
+ /** Optional override used by tests / transitional callers. Pass `null` to clear. */
16
+ export function setDiscordAgentDeps(deps) {
17
+ override = deps;
18
+ }
19
+ function lookup(endpointId) {
20
+ const registered = endpoints.get(endpointId);
21
+ if (!registered)
22
+ throw new Error(`Endpoint ${endpointId} 不存在`);
23
+ return registered;
24
+ }
25
+ export function getDiscordAgentDeps() {
26
+ if (override)
27
+ return override;
28
+ return {
29
+ getEndpoint: lookup,
30
+ getGatewayEndpoint: lookup,
31
+ };
32
+ }