-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathindex.ts
414 lines (368 loc) · 13.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
import {
getEmbeddingZeroVector,
stringToUuid,
elizaLogger,
Character,
Client as ElizaClient,
IAgentRuntime,
} from "@elizaos/core";
import {
Client,
Events,
GatewayIntentBits,
Guild,
MessageReaction,
Partials,
User,
} from "discord.js";
import { EventEmitter } from "events";
import chat_with_attachments from "./actions/chat_with_attachments.ts";
import download_media from "./actions/download_media.ts";
import joinvoice from "./actions/joinvoice.ts";
import leavevoice from "./actions/leavevoice.ts";
import summarize from "./actions/summarize_conversation.ts";
import transcribe_media from "./actions/transcribe_media.ts";
import { MessageManager } from "./messages.ts";
import channelStateProvider from "./providers/channelState.ts";
import voiceStateProvider from "./providers/voiceState.ts";
import { VoiceManager } from "./voice.ts";
import { PermissionsBitField } from "discord.js";
export class DiscordClient extends EventEmitter {
apiToken: string;
client: Client;
runtime: IAgentRuntime;
character: Character;
private messageManager: MessageManager;
private voiceManager: VoiceManager;
constructor(runtime: IAgentRuntime) {
super();
this.apiToken = runtime.getSetting("DISCORD_API_TOKEN") as string;
this.client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.DirectMessageTyping,
GatewayIntentBits.GuildMessageTyping,
GatewayIntentBits.GuildMessageReactions,
],
partials: [
Partials.Channel,
Partials.Message,
Partials.User,
Partials.Reaction,
],
});
this.runtime = runtime;
this.voiceManager = new VoiceManager(this);
this.messageManager = new MessageManager(this, this.voiceManager);
this.client.once(Events.ClientReady, this.onClientReady.bind(this));
this.client.login(this.apiToken);
this.setupEventListeners();
this.runtime.registerAction(joinvoice);
this.runtime.registerAction(leavevoice);
this.runtime.registerAction(summarize);
this.runtime.registerAction(chat_with_attachments);
this.runtime.registerAction(transcribe_media);
this.runtime.registerAction(download_media);
this.runtime.providers.push(channelStateProvider);
this.runtime.providers.push(voiceStateProvider);
}
private setupEventListeners() {
// When joining to a new server
this.client.on("guildCreate", this.handleGuildCreate.bind(this));
this.client.on(
Events.MessageReactionAdd,
this.handleReactionAdd.bind(this)
);
this.client.on(
Events.MessageReactionRemove,
this.handleReactionRemove.bind(this)
);
// Handle voice events with the voice manager
this.client.on(
"voiceStateUpdate",
this.voiceManager.handleVoiceStateUpdate.bind(this.voiceManager)
);
this.client.on(
"userStream",
this.voiceManager.handleUserStream.bind(this.voiceManager)
);
// Handle a new message with the message manager
this.client.on(
Events.MessageCreate,
this.messageManager.handleMessage.bind(this.messageManager)
);
// Handle a new interaction
this.client.on(
Events.InteractionCreate,
this.handleInteractionCreate.bind(this)
);
}
async stop() {
try {
// disconnect websocket
// this unbinds all the listeners
await this.client.destroy();
} catch (e) {
elizaLogger.error("client-discord instance stop err", e);
}
}
private async onClientReady(readyClient: { user: { tag: any; id: any } }) {
elizaLogger.success(`Logged in as ${readyClient.user?.tag}`);
// Register slash commands
const commands = [
{
name: "joinchannel",
description: "Join a voice channel",
options: [
{
name: "channel",
type: 7, // CHANNEL type
description: "The voice channel to join",
required: true,
channel_types: [2], // GuildVoice type
},
],
},
{
name: "leavechannel",
description: "Leave the current voice channel",
},
];
try {
await this.client.application?.commands.set(commands);
elizaLogger.success("Slash commands registered");
} catch (error) {
console.error("Error registering slash commands:", error);
}
// Required permissions for the bot
const requiredPermissions = [
// Text Permissions
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.SendMessages,
PermissionsBitField.Flags.SendMessagesInThreads,
PermissionsBitField.Flags.CreatePrivateThreads,
PermissionsBitField.Flags.CreatePublicThreads,
PermissionsBitField.Flags.EmbedLinks,
PermissionsBitField.Flags.AttachFiles,
PermissionsBitField.Flags.AddReactions,
PermissionsBitField.Flags.UseExternalEmojis,
PermissionsBitField.Flags.UseExternalStickers,
PermissionsBitField.Flags.MentionEveryone,
PermissionsBitField.Flags.ManageMessages,
PermissionsBitField.Flags.ReadMessageHistory,
// Voice Permissions
PermissionsBitField.Flags.Connect,
PermissionsBitField.Flags.Speak,
PermissionsBitField.Flags.UseVAD,
PermissionsBitField.Flags.PrioritySpeaker,
].reduce((a, b) => a | b, 0n);
elizaLogger.success("Use this URL to add the bot to your server:");
elizaLogger.success(
`https://discord.com/api/oauth2/authorize?client_id=${readyClient.user?.id}&permissions=${requiredPermissions}&scope=bot%20applications.commands`
);
await this.onReady();
}
async handleReactionAdd(reaction: MessageReaction, user: User) {
try {
elizaLogger.log("Reaction added");
// Early returns
if (!reaction || !user) {
elizaLogger.warn("Invalid reaction or user");
return;
}
// Get emoji info
let emoji = reaction.emoji.name;
if (!emoji && reaction.emoji.id) {
emoji = `<:${reaction.emoji.name}:${reaction.emoji.id}>`;
}
// Fetch full message if partial
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
elizaLogger.error(
"Failed to fetch partial reaction:",
error
);
return;
}
}
// Generate IDs with timestamp to ensure uniqueness
const timestamp = Date.now();
const roomId = stringToUuid(
`${reaction.message.channel.id}-${this.runtime.agentId}`
);
const userIdUUID = stringToUuid(
`${user.id}-${this.runtime.agentId}`
);
const reactionUUID = stringToUuid(
`${reaction.message.id}-${user.id}-${emoji}-${timestamp}-${this.runtime.agentId}`
);
// Validate IDs
if (!userIdUUID || !roomId) {
elizaLogger.error("Invalid user ID or room ID", {
userIdUUID,
roomId,
});
return;
}
// Process message content
const messageContent = reaction.message.content || "";
const truncatedContent =
messageContent.length > 100
? `${messageContent.substring(0, 100)}...`
: messageContent;
const reactionMessage = `*<${emoji}>: "${truncatedContent}"*`;
// Get user info
const userName = reaction.message.author?.username || "unknown";
const name = reaction.message.author?.displayName || userName;
// Ensure connection
await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);
// Create memory with retry logic
const memory = {
id: reactionUUID,
userId: userIdUUID,
agentId: this.runtime.agentId,
content: {
text: reactionMessage,
source: "discord",
inReplyTo: stringToUuid(
`${reaction.message.id}-${this.runtime.agentId}`
),
},
roomId,
createdAt: timestamp,
embedding: getEmbeddingZeroVector(),
};
try {
await this.runtime.messageManager.createMemory(memory);
elizaLogger.debug("Reaction memory created", {
reactionId: reactionUUID,
emoji,
userId: user.id,
});
} catch (error) {
if (error.code === "23505") {
// Duplicate key error
elizaLogger.warn("Duplicate reaction memory, skipping", {
reactionId: reactionUUID,
});
return;
}
throw error; // Re-throw other errors
}
} catch (error) {
elizaLogger.error("Error handling reaction:", error);
}
}
async handleReactionRemove(reaction: MessageReaction, user: User) {
elizaLogger.log("Reaction removed");
// if (user.bot) return;
let emoji = reaction.emoji.name;
if (!emoji && reaction.emoji.id) {
emoji = `<:${reaction.emoji.name}:${reaction.emoji.id}>`;
}
// Fetch the full message if it's a partial
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error(
"Something went wrong when fetching the message:",
error
);
return;
}
}
const messageContent = reaction.message.content;
const truncatedContent =
messageContent.length > 50
? messageContent.substring(0, 50) + "..."
: messageContent;
const reactionMessage = `*Removed <${emoji} emoji> from: "${truncatedContent}"*`;
const roomId = stringToUuid(
reaction.message.channel.id + "-" + this.runtime.agentId
);
const userIdUUID = stringToUuid(user.id);
// Generate a unique UUID for the reaction removal
const reactionUUID = stringToUuid(
`${reaction.message.id}-${user.id}-${emoji}-removed-${this.runtime.agentId}`
);
const userName = reaction.message.author.username;
const name = reaction.message.author.displayName;
await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);
try {
// Save the reaction removal as a message
await this.runtime.messageManager.createMemory({
id: reactionUUID, // This is the ID of the reaction removal message
userId: userIdUUID,
agentId: this.runtime.agentId,
content: {
text: reactionMessage,
source: "discord",
inReplyTo: stringToUuid(
reaction.message.id + "-" + this.runtime.agentId
), // This is the ID of the original message
},
roomId,
createdAt: Date.now(),
embedding: getEmbeddingZeroVector(),
});
} catch (error) {
console.error("Error creating reaction removal message:", error);
}
}
private handleGuildCreate(guild: Guild) {
console.log(`Joined guild ${guild.name}`);
this.voiceManager.scanGuild(guild);
}
private async handleInteractionCreate(interaction: any) {
if (!interaction.isCommand()) return;
switch (interaction.commandName) {
case "joinchannel":
await this.voiceManager.handleJoinChannelCommand(interaction);
break;
case "leavechannel":
await this.voiceManager.handleLeaveChannelCommand(interaction);
break;
}
}
private async onReady() {
const guilds = await this.client.guilds.fetch();
for (const [, guild] of guilds) {
const fullGuild = await guild.fetch();
this.voiceManager.scanGuild(fullGuild);
}
}
}
export function startDiscord(runtime: IAgentRuntime) {
return new DiscordClient(runtime);
}
export const DiscordClientInterface: ElizaClient = {
start: async (runtime: IAgentRuntime) => new DiscordClient(runtime),
stop: async (runtime: IAgentRuntime) => {
try {
// stop it
elizaLogger.log("Stopping discord client", runtime.agentId);
await runtime.clients.discord.stop();
} catch (e) {
elizaLogger.error("client-discord interface stop error", e);
}
},
};