@zhin.js/adapter-discord 5.0.2 → 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 (73) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +46 -77
  3. package/adapters/discord.ts +46 -0
  4. package/agent/tools/add_role.ts +2 -2
  5. package/agent/tools/create_thread.ts +2 -2
  6. package/agent/tools/forum_post.ts +2 -2
  7. package/agent/tools/list_roles.ts +2 -2
  8. package/agent/tools/react.ts +2 -2
  9. package/agent/tools/remove_role.ts +2 -2
  10. package/agent/tools/send_embed.ts +2 -2
  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 +71 -0
  14. package/lib/endpoint.js +355 -0
  15. package/lib/gateway.d.ts +122 -0
  16. package/lib/gateway.js +235 -0
  17. package/lib/index.d.ts +6 -0
  18. package/lib/index.js +6 -0
  19. package/lib/platform-permit.d.ts +15 -0
  20. package/lib/{src/platform-permit.js → platform-permit.js} +1 -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 +43 -36
  26. package/plugin.ts +13 -0
  27. package/schema.json +63 -0
  28. package/src/discord-agent-deps.ts +68 -11
  29. package/src/endpoint.ts +385 -1167
  30. package/src/gateway.ts +337 -0
  31. package/src/index.ts +56 -157
  32. package/src/platform-permit.ts +1 -1
  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/agent/tools/add_role.js +0 -22
  41. package/lib/agent/tools/add_role.js.map +0 -1
  42. package/lib/agent/tools/create_thread.js +0 -23
  43. package/lib/agent/tools/create_thread.js.map +0 -1
  44. package/lib/agent/tools/forum_post.js +0 -22
  45. package/lib/agent/tools/forum_post.js.map +0 -1
  46. package/lib/agent/tools/list_roles.js +0 -20
  47. package/lib/agent/tools/list_roles.js.map +0 -1
  48. package/lib/agent/tools/react.js +0 -20
  49. package/lib/agent/tools/react.js.map +0 -1
  50. package/lib/agent/tools/remove_role.js +0 -22
  51. package/lib/agent/tools/remove_role.js.map +0 -1
  52. package/lib/agent/tools/send_embed.js +0 -40
  53. package/lib/agent/tools/send_embed.js.map +0 -1
  54. package/lib/src/adapter.js +0 -96
  55. package/lib/src/adapter.js.map +0 -1
  56. package/lib/src/discord-agent-deps.js +0 -10
  57. package/lib/src/discord-agent-deps.js.map +0 -1
  58. package/lib/src/endpoint-interactions.js +0 -284
  59. package/lib/src/endpoint-interactions.js.map +0 -1
  60. package/lib/src/endpoint.js +0 -1093
  61. package/lib/src/endpoint.js.map +0 -1
  62. package/lib/src/index.js +0 -159
  63. package/lib/src/index.js.map +0 -1
  64. package/lib/src/platform-permit.js.map +0 -1
  65. package/lib/src/segment-mapper.js +0 -2
  66. package/lib/src/segment-mapper.js.map +0 -1
  67. package/lib/src/types.js +0 -2
  68. package/lib/src/types.js.map +0 -1
  69. package/plugin.yml +0 -3
  70. package/src/adapter.ts +0 -108
  71. package/src/endpoint-interactions.ts +0 -354
  72. package/src/segment-mapper.ts +0 -1
  73. package/src/types.ts +0 -60
@@ -1,1093 +0,0 @@
1
- /**
2
- * Discord Endpoint 实现 (Gateway)
3
- */
4
- import { Client, GatewayIntentBits, EmbedBuilder, AttachmentBuilder, ChannelType, REST, Routes, ActionRowBuilder, ButtonBuilder, ButtonStyle, PermissionFlagsBits, } from 'discord.js';
5
- import { Message, segment, expandInteractiveSegmentsInContent, } from 'zhin.js';
6
- import { createReadStream, promises as fs } from 'fs';
7
- import path from "path";
8
- import { fromCanonicalSegments, toCanonicalSegments } from './segment-mapper.js';
9
- export class DiscordEndpoint extends Client {
10
- adapter;
11
- $config;
12
- slashCommandHandlers = new Map();
13
- /** message_id -> channel_id,用于在仅有 message_id 的场景执行 reaction 操作 */
14
- messageChannelMap = new Map();
15
- $connected = false;
16
- get pluginLogger() {
17
- return this.adapter.plugin.logger;
18
- }
19
- get $id() {
20
- return this.$config.name;
21
- }
22
- constructor(adapter, $config) {
23
- const intents = $config.intents || [
24
- GatewayIntentBits.Guilds,
25
- GatewayIntentBits.GuildMessages,
26
- GatewayIntentBits.MessageContent,
27
- GatewayIntentBits.DirectMessages,
28
- GatewayIntentBits.GuildMembers,
29
- GatewayIntentBits.GuildMessageReactions,
30
- ];
31
- super({ intents });
32
- this.adapter = adapter;
33
- this.$config = $config;
34
- this.$connected = false;
35
- }
36
- async handleDiscordMessage(msg) {
37
- // 忽略机器人消息
38
- if (msg.author.bot)
39
- return;
40
- const message = this.$formatMessage(msg);
41
- this.adapter.emit("message.receive", message);
42
- this.pluginLogger.debug(`${this.$config.name} recv ${message.$channel.type}(${message.$channel.id}): ${segment.raw(message.$content)}`);
43
- }
44
- async handleSlashCommand(interaction) {
45
- const commandName = interaction.commandName;
46
- const handler = this.slashCommandHandlers.get(commandName);
47
- if (handler) {
48
- try {
49
- await handler(interaction);
50
- this.pluginLogger.info(`Executed slash command: /${commandName} by ${interaction.user.tag}`);
51
- }
52
- catch (error) {
53
- this.pluginLogger.error(`Error executing slash command /${commandName}:`, error);
54
- const errorMessage = "An error occurred while executing this command.";
55
- if (interaction.replied || interaction.deferred) {
56
- await interaction.followUp({
57
- content: errorMessage,
58
- ephemeral: true,
59
- });
60
- }
61
- else {
62
- await interaction.reply({ content: errorMessage, ephemeral: true });
63
- }
64
- }
65
- }
66
- else {
67
- this.pluginLogger.warn(`Unknown slash command: /${commandName}`);
68
- if (!interaction.replied) {
69
- await interaction.reply({
70
- content: "Unknown command.",
71
- ephemeral: true,
72
- });
73
- }
74
- }
75
- }
76
- async handleButtonInteraction(interaction) {
77
- try {
78
- await interaction.deferUpdate();
79
- }
80
- catch {
81
- // already acknowledged
82
- }
83
- const channel = interaction.channel;
84
- if (!channel)
85
- return;
86
- const channelType = channel.type === ChannelType.DM ? "private" : "group";
87
- const message = Message.from(interaction, {
88
- $id: interaction.id,
89
- $adapter: "discord",
90
- $endpoint: this.$config.name,
91
- $sender: {
92
- id: interaction.user.id,
93
- name: interaction.user.username || interaction.user.displayName,
94
- },
95
- $channel: {
96
- id: channel.id,
97
- type: channelType,
98
- },
99
- $content: [{
100
- type: "action",
101
- data: {
102
- id: interaction.customId,
103
- payload: interaction.customId,
104
- sourceMessageId: interaction.message?.id,
105
- },
106
- }],
107
- $raw: interaction.customId,
108
- $timestamp: Date.now(),
109
- $recall: async () => { },
110
- $reply: async (content) => {
111
- if (!interaction.channel?.isTextBased())
112
- return "";
113
- const result = await this.sendContentToChannel(interaction.channel, content);
114
- return result.id;
115
- },
116
- });
117
- this.adapter.emit("message.receive", message);
118
- }
119
- async $connect() {
120
- return new Promise((resolve, reject) => {
121
- // 监听消息事件
122
- this.on("messageCreate", this.handleDiscordMessage.bind(this));
123
- // 监听交互事件(Slash Commands + 按钮)
124
- this.on("interactionCreate", async (interaction) => {
125
- if (interaction.isChatInputCommand() && this.$config.enableSlashCommands) {
126
- await this.handleSlashCommand(interaction);
127
- return;
128
- }
129
- if (interaction.isButton()) {
130
- await this.handleButtonInteraction(interaction);
131
- }
132
- });
133
- // 监听就绪事件
134
- this.once("clientReady", async () => {
135
- this.$connected = true;
136
- this.pluginLogger.info(`Discord endpoint ${this.$config.name} connected successfully as ${this.user?.tag}`);
137
- // 设置活动状态
138
- if (this.$config.defaultActivity) {
139
- this.user?.setActivity(this.$config.defaultActivity.name, {
140
- type: this.getActivityType(this.$config.defaultActivity.type),
141
- url: this.$config.defaultActivity.url,
142
- });
143
- }
144
- // 注册 Slash Commands
145
- if (this.$config.enableSlashCommands && this.$config.slashCommands) {
146
- await this.registerSlashCommands();
147
- }
148
- resolve();
149
- });
150
- // 监听错误事件
151
- this.on("error", (error) => {
152
- this.pluginLogger.error("Discord client error:", error);
153
- this.$connected = false;
154
- reject(error);
155
- });
156
- // 登录
157
- this.login(this.$config.token).catch((error) => {
158
- this.pluginLogger.error("Failed to login to Discord:", error);
159
- this.$connected = false;
160
- reject(error);
161
- });
162
- });
163
- }
164
- async $disconnect() {
165
- try {
166
- this.removeAllListeners();
167
- await this.destroy();
168
- this.$connected = false;
169
- this.pluginLogger.info(`Discord endpoint ${this.$config.name} disconnected`);
170
- }
171
- catch (error) {
172
- this.pluginLogger.error("Error disconnecting Discord bot:", error);
173
- throw error;
174
- }
175
- }
176
- $formatMessage(msg) {
177
- // 确定聊天类型和ID
178
- let channelType;
179
- let channelId;
180
- if (msg.channel.type === ChannelType.DM) {
181
- channelType = "private";
182
- channelId = msg.channel.id;
183
- }
184
- else if (msg.channel.type === ChannelType.GroupDM) {
185
- channelType = "group";
186
- channelId = msg.channel.id;
187
- }
188
- else {
189
- channelType = "channel";
190
- channelId = msg.channel.id;
191
- }
192
- // 转换消息内容为 segment 格式
193
- const wire = this.parseMessageContent(msg);
194
- const content = toCanonicalSegments(wire);
195
- const sender = (() => {
196
- const base = {
197
- id: msg.author.id,
198
- name: msg.member?.displayName || msg.author.displayName,
199
- };
200
- const member = msg.member;
201
- const guild = msg.guild;
202
- if (member && guild) {
203
- const tokens = [];
204
- const permChecks = [
205
- [PermissionFlagsBits.Administrator, "ADMINISTRATOR"],
206
- [PermissionFlagsBits.ManageRoles, "MANAGE_ROLES"],
207
- [PermissionFlagsBits.ModerateMembers, "MODERATE_MEMBERS"],
208
- [PermissionFlagsBits.ManageChannels, "MANAGE_CHANNELS"],
209
- [PermissionFlagsBits.ManageGuild, "MANAGE_GUILD"],
210
- ];
211
- for (const [bit, name] of permChecks) {
212
- if (member.permissions.has(bit))
213
- tokens.push(name);
214
- }
215
- if (guild.ownerId === msg.author.id) {
216
- base.role = "owner";
217
- tokens.push("guild_owner", "ADMINISTRATOR");
218
- }
219
- else if (tokens.includes("ADMINISTRATOR") || tokens.includes("MODERATE_MEMBERS")) {
220
- base.role = "admin";
221
- }
222
- else {
223
- base.role = "member";
224
- }
225
- base.permissions = tokens;
226
- }
227
- return base;
228
- })();
229
- const result = Message.from(msg, {
230
- $id: msg.id,
231
- $adapter: "discord",
232
- $endpoint: this.$config.name,
233
- $sender: sender,
234
- $channel: {
235
- id: channelId,
236
- type: channelType,
237
- },
238
- $content: content,
239
- $raw: msg.content,
240
- $timestamp: msg.createdTimestamp,
241
- $recall: async () => {
242
- await msg.delete();
243
- },
244
- $reply: async (content, quote) => {
245
- if (!Array.isArray(content))
246
- content = [content];
247
- const sendOptions = {};
248
- // 处理回复消息
249
- if (quote) {
250
- const replyId = typeof quote === "boolean" ? result.$id : quote;
251
- try {
252
- const replyMessage = await msg.channel.messages.fetch(replyId);
253
- sendOptions.reply = { messageReference: replyMessage };
254
- }
255
- catch (error) {
256
- this.pluginLogger.warn(`Could not find message to reply to: ${replyId}`);
257
- }
258
- }
259
- const res = await this.adapter.sendMessage({
260
- context: "discord",
261
- endpoint: this.$config.name,
262
- id: msg.channel.id,
263
- type: msg.channel.type,
264
- content: content,
265
- });
266
- return res;
267
- },
268
- });
269
- this.messageChannelMap.set(result.$id, channelId);
270
- return result;
271
- }
272
- // 解析 Discord 消息内容为 segment 格式
273
- parseMessageContent(msg) {
274
- const segments = [];
275
- // 回复消息处理
276
- if (msg.reference) {
277
- segments.push({
278
- type: "reply",
279
- data: {
280
- id: msg.reference.messageId,
281
- channel_id: msg.reference.channelId,
282
- guild_id: msg.reference.guildId,
283
- },
284
- });
285
- }
286
- // 文本消息(包含提及、表情等)
287
- if (msg.content) {
288
- segments.push(...this.parseTextContent(msg.content, msg));
289
- }
290
- // 附件消息
291
- for (const attachment of msg.attachments.values()) {
292
- segments.push(...this.parseAttachment(attachment));
293
- }
294
- // Embed 消息
295
- for (const embed of msg.embeds) {
296
- segments.push({
297
- type: "embed",
298
- data: {
299
- title: embed.title,
300
- description: embed.description,
301
- color: embed.color,
302
- url: embed.url,
303
- thumbnail: embed.thumbnail,
304
- image: embed.image,
305
- author: embed.author,
306
- footer: embed.footer,
307
- fields: embed.fields,
308
- timestamp: embed.timestamp,
309
- },
310
- });
311
- }
312
- // 贴纸消息
313
- for (const sticker of msg.stickers.values()) {
314
- segments.push({
315
- type: "sticker",
316
- data: {
317
- id: sticker.id,
318
- name: sticker.name,
319
- url: sticker.url,
320
- format: sticker.format,
321
- tags: sticker.tags,
322
- },
323
- });
324
- }
325
- return segments.length > 0
326
- ? segments
327
- : [{ type: "text", data: { text: "" } }];
328
- }
329
- // 解析文本内容,处理提及、频道引用、角色引用等
330
- parseTextContent(content, msg) {
331
- const segments = [];
332
- let lastIndex = 0;
333
- // 匹配用户提及 <@!?用户ID>
334
- const userMentionRegex = /<@!?(\d+)>/g;
335
- // 匹配频道提及 <#频道ID>
336
- const channelMentionRegex = /<#(\d+)>/g;
337
- // 匹配角色提及 <@&角色ID>
338
- const roleMentionRegex = /<@&(\d+)>/g;
339
- // 匹配自定义表情 <:名称:ID> 或 <a:名称:ID>
340
- const emojiRegex = /<a?:(\w+):(\d+)>/g;
341
- const allMatches = [];
342
- // 收集所有匹配项
343
- let match;
344
- while ((match = userMentionRegex.exec(content)) !== null) {
345
- allMatches.push({ match, type: "user" });
346
- }
347
- while ((match = channelMentionRegex.exec(content)) !== null) {
348
- allMatches.push({ match, type: "channel" });
349
- }
350
- while ((match = roleMentionRegex.exec(content)) !== null) {
351
- allMatches.push({ match, type: "role" });
352
- }
353
- while ((match = emojiRegex.exec(content)) !== null) {
354
- allMatches.push({ match, type: "emoji" });
355
- }
356
- // 按位置排序
357
- allMatches.sort((a, b) => a.match.index - b.match.index);
358
- // 处理每个匹配项
359
- for (const { match, type } of allMatches) {
360
- const matchStart = match.index;
361
- const matchEnd = matchStart + match[0].length;
362
- // 添加匹配项前的文本
363
- if (matchStart > lastIndex) {
364
- const beforeText = content.slice(lastIndex, matchStart);
365
- if (beforeText.trim()) {
366
- segments.push({ type: "text", data: { text: beforeText } });
367
- }
368
- }
369
- // 添加特殊内容段
370
- switch (type) {
371
- case "user":
372
- const userId = match[1];
373
- const user = msg.mentions.users.get(userId);
374
- segments.push({
375
- type: "at",
376
- data: {
377
- id: userId,
378
- name: user?.username || "Unknown",
379
- text: match[0],
380
- },
381
- });
382
- break;
383
- case "channel":
384
- const channelId = match[1];
385
- const channel = msg.mentions.channels.get(channelId);
386
- segments.push({
387
- type: "channel_mention",
388
- data: {
389
- id: channelId,
390
- name: channel?.name || "unknown-channel",
391
- text: match[0],
392
- },
393
- });
394
- break;
395
- case "role":
396
- const roleId = match[1];
397
- const role = msg.mentions.roles.get(roleId);
398
- segments.push({
399
- type: "role_mention",
400
- data: {
401
- id: roleId,
402
- name: role?.name || "unknown-role",
403
- text: match[0],
404
- },
405
- });
406
- break;
407
- case "emoji":
408
- const emojiName = match[1];
409
- const emojiId = match[2];
410
- const isAnimated = match[0].startsWith("<a:");
411
- segments.push({
412
- type: "emoji",
413
- data: {
414
- id: emojiId,
415
- name: emojiName,
416
- animated: isAnimated,
417
- url: `https://cdn.discordapp.com/emojis/${emojiId}.${isAnimated ? "gif" : "png"}`,
418
- text: match[0],
419
- },
420
- });
421
- break;
422
- }
423
- lastIndex = matchEnd;
424
- }
425
- // 添加最后剩余的文本
426
- if (lastIndex < content.length) {
427
- const remainingText = content.slice(lastIndex);
428
- if (remainingText.trim()) {
429
- segments.push({ type: "text", data: { text: remainingText } });
430
- }
431
- }
432
- return segments.length > 0
433
- ? segments
434
- : [{ type: "text", data: { text: content } }];
435
- }
436
- // 解析附件
437
- parseAttachment(attachment) {
438
- const segments = [];
439
- if (attachment.contentType?.startsWith("image/")) {
440
- segments.push({
441
- type: "image",
442
- data: {
443
- id: attachment.id,
444
- name: attachment.name,
445
- url: attachment.url,
446
- proxy_url: attachment.proxyURL,
447
- size: attachment.size,
448
- width: attachment.width,
449
- height: attachment.height,
450
- content_type: attachment.contentType,
451
- },
452
- });
453
- }
454
- else if (attachment.contentType?.startsWith("audio/")) {
455
- segments.push({
456
- type: "audio",
457
- data: {
458
- id: attachment.id,
459
- name: attachment.name,
460
- url: attachment.url,
461
- proxy_url: attachment.proxyURL,
462
- size: attachment.size,
463
- content_type: attachment.contentType,
464
- },
465
- });
466
- }
467
- else if (attachment.contentType?.startsWith("video/")) {
468
- segments.push({
469
- type: "video",
470
- data: {
471
- id: attachment.id,
472
- name: attachment.name,
473
- url: attachment.url,
474
- proxy_url: attachment.proxyURL,
475
- size: attachment.size,
476
- width: attachment.width,
477
- height: attachment.height,
478
- content_type: attachment.contentType,
479
- },
480
- });
481
- }
482
- else {
483
- segments.push({
484
- type: "file",
485
- data: {
486
- id: attachment.id,
487
- name: attachment.name,
488
- url: attachment.url,
489
- proxy_url: attachment.proxyURL,
490
- size: attachment.size,
491
- content_type: attachment.contentType,
492
- },
493
- });
494
- }
495
- return segments;
496
- }
497
- async $sendMessage(options) {
498
- try {
499
- const channel = await this.channels.fetch(options.id);
500
- if (!channel || !channel.isTextBased()) {
501
- throw new Error(`Channel ${options.id} is not a text channel`);
502
- }
503
- const canonical = expandInteractiveSegmentsInContent(options.content);
504
- const wire = fromCanonicalSegments(canonical);
505
- const result = await this.sendContentToChannel(channel, wire);
506
- this.messageChannelMap.set(result.id, options.id);
507
- this.pluginLogger.debug(`${this.$config.name} send ${options.type}(${options.id}): ${segment.raw(options.content)}`);
508
- return result.id;
509
- }
510
- catch (error) {
511
- this.pluginLogger.error("Failed to send Discord message:", error);
512
- throw error;
513
- }
514
- }
515
- // 发送内容到频道
516
- async sendContentToChannel(channel, content, extraOptions = {}) {
517
- if (!Array.isArray(content))
518
- content = [content];
519
- const messageOptions = { ...extraOptions };
520
- let textContent = "";
521
- const embeds = [];
522
- const files = [];
523
- for (const segment of content) {
524
- if (typeof segment === "string") {
525
- textContent += segment;
526
- continue;
527
- }
528
- const { type, data } = segment;
529
- switch (type) {
530
- case "text":
531
- textContent += data.text || "";
532
- break;
533
- case "at":
534
- textContent += `<@${data.id}>`;
535
- break;
536
- case "channel_mention":
537
- textContent += `<#${data.id}>`;
538
- break;
539
- case "role_mention":
540
- textContent += `<@&${data.id}>`;
541
- break;
542
- case "emoji":
543
- textContent += data.animated
544
- ? `<a:${data.name}:${data.id}>`
545
- : `<:${data.name}:${data.id}>`;
546
- break;
547
- case "image":
548
- case "audio":
549
- case "video":
550
- case "file":
551
- await this.handleFileSegment(data, files, textContent);
552
- break;
553
- case "embed":
554
- embeds.push(this.createEmbedFromData(data));
555
- break;
556
- case "keyboard": {
557
- const components = (data.rows ?? []).map((row) => new ActionRowBuilder().addComponents(...row.map((btn) => {
558
- const b = new ButtonBuilder()
559
- .setCustomId(String(btn.payload).slice(0, 100))
560
- .setLabel(btn.label)
561
- .setDisabled(!!btn.disabled);
562
- if (btn.style === "danger")
563
- b.setStyle(ButtonStyle.Danger);
564
- else if (btn.style === "primary")
565
- b.setStyle(ButtonStyle.Primary);
566
- else
567
- b.setStyle(ButtonStyle.Secondary);
568
- return b;
569
- })));
570
- messageOptions.components = components;
571
- break;
572
- }
573
- default:
574
- // 未知类型作为文本处理
575
- textContent += data.text || `[${type}]`;
576
- }
577
- }
578
- // 设置消息内容
579
- if (textContent.trim()) {
580
- messageOptions.content = textContent.trim();
581
- }
582
- if (embeds.length > 0) {
583
- messageOptions.embeds = embeds.slice(0, 10); // Discord 限制最多10个embed
584
- }
585
- if (files.length > 0) {
586
- messageOptions.files = files;
587
- }
588
- // 发送消息
589
- return await channel.send(messageOptions);
590
- }
591
- async $editMessage(options) {
592
- const channel = await this.channels.fetch(options.id);
593
- if (!channel || !channel.isTextBased()) {
594
- throw new Error(`Channel ${options.id} is not a text channel`);
595
- }
596
- const msg = await channel.messages.fetch(options.messageId);
597
- const messageOptions = {};
598
- let textContent = "";
599
- if (!Array.isArray(options.content))
600
- options.content = [options.content];
601
- for (const seg of options.content) {
602
- if (typeof seg === "string") {
603
- textContent += seg;
604
- continue;
605
- }
606
- if (seg.type === "text")
607
- textContent += seg.data.text || "";
608
- if (seg.type === "keyboard") {
609
- messageOptions.components = (seg.data.rows ?? []).map((row) => new ActionRowBuilder().addComponents(...row.map((btn) => {
610
- const b = new ButtonBuilder()
611
- .setCustomId(String(btn.payload).slice(0, 100))
612
- .setLabel(btn.label)
613
- .setDisabled(!!btn.disabled);
614
- if (btn.style === "danger")
615
- b.setStyle(ButtonStyle.Danger);
616
- else if (btn.style === "primary")
617
- b.setStyle(ButtonStyle.Primary);
618
- else
619
- b.setStyle(ButtonStyle.Secondary);
620
- return b;
621
- })));
622
- }
623
- }
624
- if (textContent.trim())
625
- messageOptions.content = textContent.trim();
626
- await msg.edit(messageOptions);
627
- }
628
- async $recallMessage(id) { }
629
- // ==================== 服务器管理 API ====================
630
- /**
631
- * 踢出成员
632
- * @param guildId 服务器 ID
633
- * @param userId 用户 ID
634
- * @param reason 原因
635
- */
636
- async kickMember(guildId, userId, reason) {
637
- try {
638
- const guild = await this.guilds.fetch(guildId);
639
- const member = await guild.members.fetch(userId);
640
- await member.kick(reason);
641
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 踢出成员 ${userId}(服务器 ${guildId})`);
642
- return true;
643
- }
644
- catch (error) {
645
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 踢出成员失败:`, error);
646
- throw error;
647
- }
648
- }
649
- /**
650
- * 封禁成员
651
- * @param guildId 服务器 ID
652
- * @param userId 用户 ID
653
- * @param reason 原因
654
- * @param deleteMessageDays 删除消息天数
655
- */
656
- async banMember(guildId, userId, reason, deleteMessageDays) {
657
- try {
658
- const guild = await this.guilds.fetch(guildId);
659
- await guild.members.ban(userId, { reason, deleteMessageSeconds: deleteMessageDays ? deleteMessageDays * 86400 : undefined });
660
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 封禁成员 ${userId}(服务器 ${guildId})`);
661
- return true;
662
- }
663
- catch (error) {
664
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 封禁成员失败:`, error);
665
- throw error;
666
- }
667
- }
668
- /**
669
- * 解除封禁
670
- * @param guildId 服务器 ID
671
- * @param userId 用户 ID
672
- * @param reason 原因
673
- */
674
- async unbanMember(guildId, userId, reason) {
675
- try {
676
- const guild = await this.guilds.fetch(guildId);
677
- await guild.members.unban(userId, reason);
678
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 解除封禁 ${userId}(服务器 ${guildId})`);
679
- return true;
680
- }
681
- catch (error) {
682
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 解除封禁失败:`, error);
683
- throw error;
684
- }
685
- }
686
- /**
687
- * 超时(禁言)成员
688
- * @param guildId 服务器 ID
689
- * @param userId 用户 ID
690
- * @param duration 超时时长(秒),0 表示取消超时
691
- * @param reason 原因
692
- */
693
- async timeoutMember(guildId, userId, duration = 600, reason) {
694
- try {
695
- const guild = await this.guilds.fetch(guildId);
696
- const member = await guild.members.fetch(userId);
697
- if (duration === 0) {
698
- await member.timeout(null, reason);
699
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 取消成员 ${userId} 超时(服务器 ${guildId})`);
700
- }
701
- else {
702
- await member.timeout(duration * 1000, reason);
703
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 超时成员 ${userId} ${duration}秒(服务器 ${guildId})`);
704
- }
705
- return true;
706
- }
707
- catch (error) {
708
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 超时操作失败:`, error);
709
- throw error;
710
- }
711
- }
712
- /**
713
- * 修改成员昵称
714
- * @param guildId 服务器 ID
715
- * @param userId 用户 ID
716
- * @param nickname 新昵称
717
- */
718
- async setNickname(guildId, userId, nickname) {
719
- try {
720
- const guild = await this.guilds.fetch(guildId);
721
- const member = await guild.members.fetch(userId);
722
- await member.setNickname(nickname);
723
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 设置成员 ${userId} 昵称为 "${nickname}"(服务器 ${guildId})`);
724
- return true;
725
- }
726
- catch (error) {
727
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 设置昵称失败:`, error);
728
- throw error;
729
- }
730
- }
731
- /**
732
- * 添加角色
733
- * @param guildId 服务器 ID
734
- * @param userId 用户 ID
735
- * @param roleId 角色 ID
736
- */
737
- async addRole(guildId, userId, roleId) {
738
- try {
739
- const guild = await this.guilds.fetch(guildId);
740
- const member = await guild.members.fetch(userId);
741
- await member.roles.add(roleId);
742
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 给成员 ${userId} 添加角色 ${roleId}(服务器 ${guildId})`);
743
- return true;
744
- }
745
- catch (error) {
746
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 添加角色失败:`, error);
747
- throw error;
748
- }
749
- }
750
- /**
751
- * 移除角色
752
- * @param guildId 服务器 ID
753
- * @param userId 用户 ID
754
- * @param roleId 角色 ID
755
- */
756
- async removeRole(guildId, userId, roleId) {
757
- try {
758
- const guild = await this.guilds.fetch(guildId);
759
- const member = await guild.members.fetch(userId);
760
- await member.roles.remove(roleId);
761
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 移除成员 ${userId} 的角色 ${roleId}(服务器 ${guildId})`);
762
- return true;
763
- }
764
- catch (error) {
765
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 移除角色失败:`, error);
766
- throw error;
767
- }
768
- }
769
- /**
770
- * 获取服务器角色列表
771
- * @param guildId 服务器 ID
772
- */
773
- async getRoles(guildId) {
774
- try {
775
- const guild = await this.guilds.fetch(guildId);
776
- await guild.roles.fetch();
777
- return guild.roles.cache.map(role => ({
778
- id: role.id,
779
- name: role.name,
780
- color: role.hexColor,
781
- position: role.position,
782
- permissions: role.permissions.bitfield.toString(),
783
- }));
784
- }
785
- catch (error) {
786
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 获取角色列表失败:`, error);
787
- throw error;
788
- }
789
- }
790
- /**
791
- * 获取成员列表
792
- * @param guildId 服务器 ID
793
- * @param limit 数量限制
794
- */
795
- async getMembers(guildId, limit = 100) {
796
- try {
797
- const guild = await this.guilds.fetch(guildId);
798
- const members = await guild.members.fetch({ limit });
799
- return Array.from(members.values()).map(member => ({
800
- id: member.id,
801
- username: member.user.username,
802
- nickname: member.nickname,
803
- roles: member.roles.cache.map(r => r.id),
804
- joined_at: member.joinedAt?.toISOString(),
805
- }));
806
- }
807
- catch (error) {
808
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 获取成员列表失败:`, error);
809
- throw error;
810
- }
811
- }
812
- /**
813
- * 获取服务器信息
814
- * @param guildId 服务器 ID
815
- */
816
- async getGuildInfo(guildId) {
817
- try {
818
- const guild = await this.guilds.fetch(guildId);
819
- return {
820
- id: guild.id,
821
- name: guild.name,
822
- icon: guild.iconURL(),
823
- owner_id: guild.ownerId,
824
- member_count: guild.memberCount,
825
- created_at: guild.createdAt?.toISOString(),
826
- };
827
- }
828
- catch (error) {
829
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 获取服务器信息失败:`, error);
830
- throw error;
831
- }
832
- }
833
- async createThread(channelId, name, messageId, autoArchiveDuration) {
834
- try {
835
- const channel = await this.channels.fetch(channelId);
836
- if (!channel || !('threads' in channel))
837
- throw new Error(`Channel ${channelId} 不支持创建帖子`);
838
- const options = { name, autoArchiveDuration: autoArchiveDuration || 1440 };
839
- if (messageId)
840
- options.startMessage = messageId;
841
- const thread = await channel.threads.create(options);
842
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 创建帖子 "${name}" (channel ${channelId})`);
843
- return thread;
844
- }
845
- catch (error) {
846
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 创建帖子失败:`, error);
847
- throw error;
848
- }
849
- }
850
- async addReaction(channelId, messageId, emoji) {
851
- try {
852
- const channel = await this.channels.fetch(channelId);
853
- if (!channel || !channel.isTextBased())
854
- throw new Error(`Channel ${channelId} 不是文本频道`);
855
- const message = await channel.messages.fetch(messageId);
856
- await message.react(emoji);
857
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 添加反应 ${emoji} (message ${messageId})`);
858
- }
859
- catch (error) {
860
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 添加反应失败:`, error);
861
- throw error;
862
- }
863
- }
864
- resolveDiscordMessageRef(messageId) {
865
- if (messageId.includes(':')) {
866
- const [channelId, msgId] = messageId.split(':');
867
- if (channelId && msgId) {
868
- this.messageChannelMap.set(msgId, channelId);
869
- return { channelId, msgId };
870
- }
871
- }
872
- const channelId = this.messageChannelMap.get(messageId);
873
- if (!channelId)
874
- return null;
875
- return { channelId, msgId: messageId };
876
- }
877
- async $addReaction(messageId, emoji) {
878
- const ref = this.resolveDiscordMessageRef(messageId);
879
- if (!ref) {
880
- this.pluginLogger.warn(`Discord Endpoint ${this.$id} 无法根据 message_id=${messageId} 定位 channel_id,跳过 addReaction`);
881
- return null;
882
- }
883
- try {
884
- await this.addReaction(ref.channelId, ref.msgId, emoji);
885
- return emoji;
886
- }
887
- catch (error) {
888
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 添加 reaction 失败:`, error);
889
- return null;
890
- }
891
- }
892
- async $removeReaction(messageId, reactionId) {
893
- const ref = this.resolveDiscordMessageRef(messageId);
894
- if (!ref) {
895
- this.pluginLogger.warn(`Discord Endpoint ${this.$id} 无法根据 message_id=${messageId} 定位 channel_id,跳过 removeReaction`);
896
- return;
897
- }
898
- try {
899
- const channel = await this.channels.fetch(ref.channelId);
900
- if (!channel || !channel.isTextBased())
901
- return;
902
- const message = await channel.messages.fetch(ref.msgId);
903
- const targetReaction = message.reactions.resolve(reactionId) ||
904
- message.reactions.cache.find((reaction) => reaction.emoji.toString() === reactionId ||
905
- reaction.emoji.name === reactionId ||
906
- reaction.emoji.id === reactionId);
907
- if (targetReaction && this.user?.id) {
908
- await targetReaction.users.remove(this.user.id);
909
- }
910
- }
911
- catch (error) {
912
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 移除 reaction 失败:`, error);
913
- }
914
- }
915
- async sendEmbed(channelId, embedData) {
916
- try {
917
- const channel = await this.channels.fetch(channelId);
918
- if (!channel || !channel.isTextBased())
919
- throw new Error(`Channel ${channelId} 不是文本频道`);
920
- const embed = this.createEmbedFromData(embedData);
921
- const msg = await channel.send({ embeds: [embed] });
922
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 发送 Embed 到 ${channelId}`);
923
- return msg;
924
- }
925
- catch (error) {
926
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 发送 Embed 失败:`, error);
927
- throw error;
928
- }
929
- }
930
- async createForumPost(channelId, name, content, tags) {
931
- try {
932
- const channel = await this.channels.fetch(channelId);
933
- if (!channel || channel.type !== ChannelType.GuildForum)
934
- throw new Error(`Channel ${channelId} 不是论坛频道`);
935
- const forumChannel = channel;
936
- const options = {
937
- name,
938
- message: { content },
939
- };
940
- if (tags?.length && forumChannel.availableTags?.length) {
941
- const tagIds = forumChannel.availableTags
942
- .filter((t) => tags.includes(t.name))
943
- .map((t) => t.id);
944
- if (tagIds.length)
945
- options.appliedTags = tagIds;
946
- }
947
- const thread = await forumChannel.threads.create(options);
948
- this.pluginLogger.info(`Discord Endpoint ${this.$id} 创建论坛帖 "${name}" (channel ${channelId})`);
949
- return thread;
950
- }
951
- catch (error) {
952
- this.pluginLogger.error(`Discord Endpoint ${this.$id} 创建论坛帖失败:`, error);
953
- throw error;
954
- }
955
- }
956
- // 处理文件段
957
- async handleFileSegment(data, files, textContent) {
958
- if (data.file && (await this.fileExists(data.file))) {
959
- // 本地文件
960
- files.push(new AttachmentBuilder(createReadStream(data.file), {
961
- name: data.name || path.basename(data.file),
962
- }));
963
- }
964
- else if (data.url) {
965
- // URL 文件
966
- files.push(new AttachmentBuilder(data.url, {
967
- name: data.name || "attachment",
968
- }));
969
- }
970
- else if (data.buffer) {
971
- // Buffer 数据
972
- files.push(new AttachmentBuilder(data.buffer, {
973
- name: data.name || "attachment",
974
- }));
975
- }
976
- }
977
- // 从数据创建 Embed
978
- createEmbedFromData(data) {
979
- const embed = new EmbedBuilder();
980
- if (data.title)
981
- embed.setTitle(data.title);
982
- if (data.description)
983
- embed.setDescription(data.description);
984
- if (data.color)
985
- embed.setColor(data.color);
986
- if (data.url)
987
- embed.setURL(data.url);
988
- if (data.thumbnail?.url)
989
- embed.setThumbnail(data.thumbnail.url);
990
- if (data.image?.url)
991
- embed.setImage(data.image.url);
992
- if (data.author)
993
- embed.setAuthor(data.author);
994
- if (data.footer)
995
- embed.setFooter(data.footer);
996
- if (data.timestamp)
997
- embed.setTimestamp(new Date(data.timestamp));
998
- if (data.fields && Array.isArray(data.fields)) {
999
- embed.addFields(data.fields);
1000
- }
1001
- return embed;
1002
- }
1003
- // 工具方法:获取活动类型
1004
- getActivityType(type) {
1005
- const activityTypes = {
1006
- PLAYING: 0,
1007
- STREAMING: 1,
1008
- LISTENING: 2,
1009
- WATCHING: 3,
1010
- COMPETING: 5,
1011
- };
1012
- return activityTypes[type] || 0;
1013
- }
1014
- // 注册 Slash Commands
1015
- async registerSlashCommands() {
1016
- if (!this.$config.slashCommands || !this.user)
1017
- return;
1018
- try {
1019
- const rest = new REST({ version: "10" }).setToken(this.$config.token);
1020
- if (this.$config.globalCommands) {
1021
- // 注册全局命令
1022
- await rest.put(Routes.applicationCommands(this.user.id), {
1023
- body: this.$config.slashCommands,
1024
- });
1025
- this.pluginLogger.info("Successfully registered global slash commands");
1026
- }
1027
- else {
1028
- // 为每个服务器注册命令
1029
- for (const guild of this.guilds.cache.values()) {
1030
- await rest.put(Routes.applicationGuildCommands(this.user.id, guild.id), { body: this.$config.slashCommands });
1031
- }
1032
- this.pluginLogger.info("Successfully registered guild slash commands");
1033
- }
1034
- }
1035
- catch (error) {
1036
- this.pluginLogger.error("Failed to register slash commands:", error);
1037
- }
1038
- }
1039
- // 添加 Slash Command 处理器
1040
- addSlashCommandHandler(commandName, handler) {
1041
- this.slashCommandHandlers.set(commandName, handler);
1042
- }
1043
- // 移除 Slash Command 处理器
1044
- removeSlashCommandHandler(commandName) {
1045
- return this.slashCommandHandlers.delete(commandName);
1046
- }
1047
- // 工具方法:检查文件是否存在
1048
- async fileExists(filePath) {
1049
- try {
1050
- await fs.access(filePath);
1051
- return true;
1052
- }
1053
- catch {
1054
- return false;
1055
- }
1056
- }
1057
- // 静态方法:格式化内容为文本(用于日志显示)
1058
- static formatContentToText(content) {
1059
- if (!Array.isArray(content))
1060
- content = [content];
1061
- return content
1062
- .map((segment) => {
1063
- if (typeof segment === "string")
1064
- return segment;
1065
- switch (segment.type) {
1066
- case "text":
1067
- return segment.data.text || "";
1068
- case "at":
1069
- return `@${segment.data.name || segment.data.id}`;
1070
- case "channel_mention":
1071
- return `#${segment.data.name}`;
1072
- case "role_mention":
1073
- return `@${segment.data.name}`;
1074
- case "image":
1075
- return "[图片]";
1076
- case "audio":
1077
- return "[音频]";
1078
- case "video":
1079
- return "[视频]";
1080
- case "file":
1081
- return "[文件]";
1082
- case "embed":
1083
- return "[嵌入消息]";
1084
- case "emoji":
1085
- return `:${segment.data.name}:`;
1086
- default:
1087
- return `[${segment.type}]`;
1088
- }
1089
- })
1090
- .join("");
1091
- }
1092
- }
1093
- //# sourceMappingURL=endpoint.js.map