-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Copy pathmessages.ts
927 lines (807 loc) · 30.6 KB
/
messages.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
import { composeContext } from "@ai16z/eliza/src/context.ts";
import {
generateMessageResponse,
generateShouldRespond,
} from "@ai16z/eliza/src/generation.ts";
import { embeddingZeroVector } from "@ai16z/eliza/src/memory.ts";
import {
messageCompletionFooter,
shouldRespondFooter,
} from "@ai16z/eliza/src/parsing.ts";
import {
Content,
HandlerCallback,
IAgentRuntime,
IBrowserService,
ISpeechService,
IVideoService,
Media,
Memory,
ModelClass,
ServiceType,
State,
UUID,
} from "@ai16z/eliza/src/types.ts";
import { stringToUuid } from "@ai16z/eliza/src/uuid.ts";
import { generateText, trimTokens } from "@ai16z/eliza/src/generation.ts";
import { parseJSONObjectFromText } from "@ai16z/eliza/src/parsing.ts";
import {
ChannelType,
Client,
Message as DiscordMessage,
PermissionsBitField,
TextChannel,
ThreadChannel,
} from "discord.js";
import { elizaLogger } from "@ai16z/eliza/src/logger.ts";
import { AttachmentManager } from "./attachments.ts";
import { VoiceManager } from "./voice.ts";
import { Service } from "@ai16z/eliza";
const MAX_MESSAGE_LENGTH = 1900;
async function generateSummary(
runtime: IAgentRuntime,
text: string
): Promise<{ title: string; description: string }> {
// make sure text is under 128k characters
text = trimTokens(text, 100000, "gpt-4o-mini"); // TODO: clean this up
const prompt = `Please generate a concise summary for the following text:
Text: """
${text}
"""
Respond with a JSON object in the following format:
\`\`\`json
{
"title": "Generated Title",
"summary": "Generated summary and/or description of the text"
}
\`\`\``;
const response = await generateText({
runtime,
context: prompt,
modelClass: ModelClass.SMALL,
});
const parsedResponse = parseJSONObjectFromText(response);
if (parsedResponse) {
return {
title: parsedResponse.title,
description: parsedResponse.summary,
};
}
return {
title: "",
description: "",
};
}
export type InterestChannels = {
[key: string]: {
lastMessageSent: number;
messages: { userId: UUID; userName: string; content: Content }[];
};
};
const discordShouldRespondTemplate =
`# Task: Decide if {{agentName}} should respond.
About {{agentName}}:
{{bio}}
# INSTRUCTIONS: Determine if {{agentName}} should respond to the message and participate in the conversation. Do not comment. Just respond with "RESPOND" or "IGNORE" or "STOP".
# RESPONSE EXAMPLES
<user 1>: I just saw a really great movie
<user 2>: Oh? Which movie?
Result: [IGNORE]
{{agentName}}: Oh, this is my favorite scene
<user 1>: sick
<user 2>: wait, why is it your favorite scene
Result: [RESPOND]
<user>: stfu bot
Result: [STOP]
<user>: Hey {{agent}}, can you help me with something
Result: [RESPOND]
<user>: {{agentName}} stfu plz
Result: [STOP]
<user>: i need help
{{agentName}}: how can I help you?
<user>: no. i need help from someone else
Result: [IGNORE]
<user>: Hey {{agent}}, can I ask you a question
{{agentName}}: Sure, what is it
<user>: can you ask claude to create a basic react module that demonstrates a counter
Result: [RESPOND]
<user>: {{agentName}} can you tell me a story
<user>: {about a girl named elara
{{agentName}}: Sure.
{{agentName}}: Once upon a time, in a quaint little village, there was a curious girl named Elara.
{{agentName}}: Elara was known for her adventurous spirit and her knack for finding beauty in the mundane.
<user>: I'm loving it, keep going
Result: [RESPOND]
<user>: {{agentName}} stop responding plz
Result: [STOP]
<user>: okay, i want to test something. can you say marco?
{{agentName}}: marco
<user>: great. okay, now do it again
Result: [RESPOND]
Response options are [RESPOND], [IGNORE] and [STOP].
{{agentName}} is in a room with other users and is very worried about being annoying and saying too much.
Respond with [RESPOND] to messages that are directed at {{agentName}}, or participate in conversations that are interesting or relevant to their background.
If a message is not interesting or relevant, respond with [IGNORE]
Unless directly responding to a user, respond with [IGNORE] to messages that are very short or do not contain much information.
If a user asks {{agentName}} to be quiet, respond with [STOP]
If {{agentName}} concludes a conversation and isn't part of the conversation anymore, respond with [STOP]
IMPORTANT: {{agentName}} is particularly sensitive about being annoying, so if there is any doubt, it is better to respond with [IGNORE].
If {{agentName}} is conversing with a user and they have not asked to stop, it is better to respond with [RESPOND].
{{recentMessages}}
# INSTRUCTIONS: Choose the option that best describes {{agentName}}'s response to the last message. Ignore messages if they are addressed to someone else.
` + shouldRespondFooter;
export const discordMessageHandlerTemplate =
// {{goals}}
`# Action Examples
{{actionExamples}}
(Action examples are for reference only. Do not use the information from them in your response.)
# Knowledge
{{knowledge}}
# Task: Generate dialog and actions for the character {{agentName}}.
About {{agentName}}:
{{bio}}
{{lore}}
Examples of {{agentName}}'s dialog and actions:
{{characterMessageExamples}}
{{providers}}
{{attachments}}
{{actions}}
# Capabilities
Note that {{agentName}} is capable of reading/seeing/hearing various forms of media, including images, videos, audio, plaintext and PDFs. Recent attachments have been included above under the "Attachments" section.
{{messageDirections}}
{{recentMessages}}
# Instructions: Write the next message for {{agentName}}. Include an action, if appropriate. {{actionNames}}
` + messageCompletionFooter;
export async function sendMessageInChunks(
channel: TextChannel,
content: string,
inReplyTo: string,
files: any[]
): Promise<DiscordMessage[]> {
const sentMessages: DiscordMessage[] = [];
const messages = splitMessage(content);
try {
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
if (
message.trim().length > 0 ||
(i === messages.length - 1 && files && files.length > 0)
) {
const options: any = {
content: message.trim(),
};
// if (i === 0 && inReplyTo) {
// // Reply to the specified message for the first chunk
// options.reply = {
// messageReference: inReplyTo,
// };
// }
if (i === messages.length - 1 && files && files.length > 0) {
// Attach files to the last message chunk
options.files = files;
}
const m = await channel.send(options);
sentMessages.push(m);
}
}
} catch (error) {
elizaLogger.error("Error sending message:", error);
}
return sentMessages;
}
function splitMessage(content: string): string[] {
const messages: string[] = [];
let currentMessage = "";
const rawLines = content?.split("\n") || [];
// split all lines into MAX_MESSAGE_LENGTH chunks so any long lines are split
const lines = rawLines
.map((line) => {
const chunks = [];
while (line.length > MAX_MESSAGE_LENGTH) {
chunks.push(line.slice(0, MAX_MESSAGE_LENGTH));
line = line.slice(MAX_MESSAGE_LENGTH);
}
chunks.push(line);
return chunks;
})
.flat();
for (const line of lines) {
if (currentMessage.length + line.length + 1 > MAX_MESSAGE_LENGTH) {
messages.push(currentMessage.trim());
currentMessage = "";
}
currentMessage += line + "\n";
}
if (currentMessage.trim().length > 0) {
messages.push(currentMessage.trim());
}
return messages;
}
function canSendMessage(channel) {
// if it is a DM channel, we can always send messages
if (channel.type === ChannelType.DM) {
return {
canSend: true,
reason: null,
};
}
const botMember = channel.guild?.members.cache.get(channel.client.user.id);
if (!botMember) {
return {
canSend: false,
reason: "Not a guild channel or bot member not found",
};
}
// Required permissions for sending messages
const requiredPermissions = [
PermissionsBitField.Flags.ViewChannel,
PermissionsBitField.Flags.SendMessages,
PermissionsBitField.Flags.ReadMessageHistory,
];
// Add thread-specific permission if it's a thread
if (channel instanceof ThreadChannel) {
requiredPermissions.push(
PermissionsBitField.Flags.SendMessagesInThreads
);
}
// Check permissions
const permissions = channel.permissionsFor(botMember);
if (!permissions) {
return {
canSend: false,
reason: "Could not retrieve permissions",
};
}
// Check each required permission
const missingPermissions = requiredPermissions.filter(
(perm) => !permissions.has(perm)
);
return {
canSend: missingPermissions.length === 0,
missingPermissions: missingPermissions,
reason:
missingPermissions.length > 0
? `Missing permissions: ${missingPermissions.map((p) => String(p)).join(", ")}`
: null,
};
}
export class MessageManager {
private client: Client;
private runtime: IAgentRuntime;
private attachmentManager: AttachmentManager;
private interestChannels: InterestChannels = {};
private discordClient: any;
private voiceManager: VoiceManager;
constructor(discordClient: any, voiceManager: VoiceManager) {
this.client = discordClient.client;
this.voiceManager = voiceManager;
this.discordClient = discordClient;
this.runtime = discordClient.runtime;
this.attachmentManager = new AttachmentManager(this.runtime);
}
async handleMessage(message: DiscordMessage) {
if (
message.interaction ||
message.author.id ===
this.client.user?.id /* || message.author?.bot*/
)
return;
const userId = message.author.id as UUID;
const userName = message.author.username;
const name = message.author.displayName;
const channelId = message.channel.id;
try {
const { processedContent, attachments } =
await this.processMessageMedia(message);
const audioAttachments = message.attachments.filter((attachment) =>
attachment.contentType?.startsWith("audio/")
);
if (audioAttachments.size > 0) {
const processedAudioAttachments =
await this.attachmentManager.processAttachments(
audioAttachments
);
attachments.push(...processedAudioAttachments);
}
const roomId = stringToUuid(channelId + "-" + this.runtime.agentId);
const userIdUUID = stringToUuid(userId);
await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);
const messageId = stringToUuid(
message.id + "-" + this.runtime.agentId
);
let shouldIgnore = false;
let shouldRespond = true;
const content: Content = {
text: processedContent,
attachments: attachments,
source: "discord",
url: message.url,
inReplyTo: message.reference?.messageId
? stringToUuid(
message.reference.messageId +
"-" +
this.runtime.agentId
)
: undefined,
};
const userMessage = {
content,
userId: userIdUUID,
agentId: this.runtime.agentId,
roomId,
};
const memory: Memory = {
id: stringToUuid(message.id + "-" + this.runtime.agentId),
...userMessage,
userId: userIdUUID,
agentId: this.runtime.agentId,
roomId,
content,
createdAt: message.createdTimestamp,
embedding: embeddingZeroVector,
};
if (content.text) {
await this.runtime.messageManager.createMemory(memory);
}
let state = (await this.runtime.composeState(userMessage, {
discordClient: this.client,
discordMessage: message,
agentName:
this.runtime.character.name ||
this.client.user?.displayName,
})) as State;
if (!canSendMessage(message.channel).canSend) {
return elizaLogger.warn(
`Cannot send message to channel ${message.channel}`,
canSendMessage(message.channel)
);
}
if (!shouldIgnore) {
shouldIgnore = await this._shouldIgnore(message);
}
if (shouldIgnore) {
return;
}
const hasInterest = this._checkInterest(channelId);
const agentUserState =
await this.runtime.databaseAdapter.getParticipantUserState(
roomId,
this.runtime.agentId
);
if (
agentUserState === "MUTED" &&
!message.mentions.has(this.client.user.id) &&
!hasInterest
) {
console.log("Ignoring muted room");
// Ignore muted rooms unless explicitly mentioned
return;
}
if (agentUserState === "FOLLOWED") {
shouldRespond = true; // Always respond in followed rooms
} else if (
(!shouldRespond && hasInterest) ||
(shouldRespond && !hasInterest)
) {
shouldRespond = await this._shouldRespond(message, state);
}
if (shouldRespond) {
const context = composeContext({
state,
template:
this.runtime.character.templates
?.discordMessageHandlerTemplate ||
discordMessageHandlerTemplate,
});
const responseContent = await this._generateResponse(
memory,
state,
context
);
responseContent.text = responseContent.text?.trim();
responseContent.inReplyTo = stringToUuid(
message.id + "-" + this.runtime.agentId
);
if (!responseContent.text) {
return;
}
const callback: HandlerCallback = async (
content: Content,
files: any[]
) => {
try {
if (message.id && !content.inReplyTo) {
content.inReplyTo = stringToUuid(
message.id + "-" + this.runtime.agentId
);
}
if (false) {
// For voice channels, use text-to-speech
const audioStream = await this.runtime
.getService(ServiceType.SPEECH_GENERATION)
.getInstance<ISpeechService>()
.generate(this.runtime, content.text);
await this.voiceManager.playAudioStream(
userId,
audioStream
);
const memory: Memory = {
id: stringToUuid(
message.id + "-" + this.runtime.agentId
),
userId: this.runtime.agentId,
agentId: this.runtime.agentId,
content,
roomId,
embedding: embeddingZeroVector,
};
return [memory];
} else {
// For text channels, send the message
const messages = await sendMessageInChunks(
message.channel as TextChannel,
content.text,
message.id,
files
);
const memories: Memory[] = [];
for (const m of messages) {
let action = content.action;
// If there's only one message or it's the last message, keep the original action
// For multiple messages, set all but the last to 'CONTINUE'
if (
messages.length > 1 &&
m !== messages[messages.length - 1]
) {
action = "CONTINUE";
}
const memory: Memory = {
id: stringToUuid(
m.id + "-" + this.runtime.agentId
),
userId: this.runtime.agentId,
agentId: this.runtime.agentId,
content: {
...content,
action,
inReplyTo: messageId,
url: m.url,
},
roomId,
embedding: embeddingZeroVector,
createdAt: m.createdTimestamp,
};
memories.push(memory);
}
for (const m of memories) {
await this.runtime.messageManager.createMemory(
m
);
}
return memories;
}
} catch (error) {
console.error("Error sending message:", error);
return [];
}
};
const responseMessages = await callback(responseContent);
state = await this.runtime.updateRecentMessageState(state);
await this.runtime.processActions(
memory,
responseMessages,
state,
callback
);
}
await this.runtime.evaluate(memory, state, shouldRespond);
} catch (error) {
console.error("Error handling message:", error);
if (message.channel.type === ChannelType.GuildVoice) {
// For voice channels, use text-to-speech for the error message
const errorMessage = "Sorry, I had a glitch. What was that?";
const audioStream = await this.runtime
.getService(ServiceType.SPEECH_GENERATION)
.getInstance<ISpeechService>()
.generate(this.runtime, errorMessage);
await this.voiceManager.playAudioStream(userId, audioStream);
} else {
// For text channels, send the error message
console.error("Error sending message:", error);
}
}
}
async cacheMessages(channel: TextChannel, count: number = 20) {
const messages = await channel.messages.fetch({ limit: count });
// TODO: This is throwing an error but seems to work?
for (const [_, message] of messages) {
await this.handleMessage(message);
}
}
async processMessageMedia(
message: DiscordMessage
): Promise<{ processedContent: string; attachments: Media[] }> {
let processedContent = message.content;
let attachments: Media[] = [];
// Process code blocks in the message content
const codeBlockRegex = /```([\s\S]*?)```/g;
let match;
while ((match = codeBlockRegex.exec(processedContent))) {
const codeBlock = match[1];
const lines = codeBlock.split("\n");
const title = lines[0];
const description = lines.slice(0, 3).join("\n");
const attachmentId =
`code-${Date.now()}-${Math.floor(Math.random() * 1000)}`.slice(
-5
);
attachments.push({
id: attachmentId,
url: "",
title: title || "Code Block",
source: "Code",
description: description,
text: codeBlock,
});
processedContent = processedContent.replace(
match[0],
`Code Block (${attachmentId})`
);
}
// Process message attachments
if (message.attachments.size > 0) {
attachments = await this.attachmentManager.processAttachments(
message.attachments
);
}
// TODO: Move to attachments manager
const urlRegex = /(https?:\/\/[^\s]+)/g;
const urls = processedContent.match(urlRegex) || [];
for (const url of urls) {
if (
this.runtime
.getService(ServiceType.VIDEO)
.getInstance<IVideoService>()
.isVideoUrl(url)
) {
const videoInfo = await this.runtime
.getService(ServiceType.VIDEO)
.getInstance<IVideoService>()
.processVideo(url);
attachments.push({
id: `youtube-${Date.now()}`,
url: url,
title: videoInfo.title,
source: "YouTube",
description: videoInfo.description,
text: videoInfo.text,
});
} else {
const { title, bodyContent } = await this.runtime
.getService(ServiceType.BROWSER)
.getInstance<IBrowserService>()
.getPageContent(url, this.runtime);
const { title: newTitle, description } = await generateSummary(
this.runtime,
title + "\n" + bodyContent
);
attachments.push({
id: `webpage-${Date.now()}`,
url: url,
title: newTitle || "Web Page",
source: "Web",
description,
text: bodyContent,
});
}
}
return { processedContent, attachments };
}
private _checkInterest(channelId: string): boolean {
return !!this.interestChannels[channelId];
}
private async _shouldIgnore(message: DiscordMessage): Promise<boolean> {
// if the message is from us, ignore
if (message.author.id === this.client.user?.id) return true;
let messageContent = message.content.toLowerCase();
// Replace the bot's @ping with the character name
const botMention = `<@!?${this.client.user?.id}>`;
messageContent = messageContent.replace(
new RegExp(botMention, "gi"),
this.runtime.character.name.toLowerCase()
);
// Replace the bot's username with the character name
const botUsername = this.client.user?.username.toLowerCase();
messageContent = messageContent.replace(
new RegExp(`\\b${botUsername}\\b`, "g"),
this.runtime.character.name.toLowerCase()
);
// strip all special characters
messageContent = messageContent.replace(/[^a-zA-Z0-9\s]/g, "");
// short responses where ruby should stop talking and disengage unless mentioned again
const loseInterestWords = [
"shut up",
"stop",
"please shut up",
"shut up please",
"dont talk",
"silence",
"stop talking",
"be quiet",
"hush",
"wtf",
"chill",
"stfu",
"stupid bot",
"dumb bot",
"stop responding",
"god damn it",
"god damn",
"goddamnit",
"can you not",
"can you stop",
"be quiet",
"hate you",
"hate this",
"fuck up",
];
if (
messageContent.length < 100 &&
loseInterestWords.some((word) => messageContent.includes(word))
) {
delete this.interestChannels[message.channelId];
return true;
}
// If we're not interested in the channel and it's a short message, ignore it
if (
messageContent.length < 10 &&
!this.interestChannels[message.channelId]
) {
return true;
}
const targetedPhrases = [
this.runtime.character.name + " stop responding",
this.runtime.character.name + " stop talking",
this.runtime.character.name + " shut up",
this.runtime.character.name + " stfu",
"stop talking" + this.runtime.character.name,
this.runtime.character.name + " stop talking",
"shut up " + this.runtime.character.name,
this.runtime.character.name + " shut up",
"stfu " + this.runtime.character.name,
this.runtime.character.name + " stfu",
"chill" + this.runtime.character.name,
this.runtime.character.name + " chill",
];
// lose interest if pinged and told to stop responding
if (targetedPhrases.some((phrase) => messageContent.includes(phrase))) {
delete this.interestChannels[message.channelId];
return true;
}
// if the message is short, ignore but maintain interest
if (
!this.interestChannels[message.channelId] &&
messageContent.length < 2
) {
return true;
}
const ignoreResponseWords = [
"lol",
"nm",
"uh",
"wtf",
"stfu",
"dumb",
"jfc",
"omg",
];
if (
message.content.length < 4 &&
ignoreResponseWords.some((word) =>
message.content.toLowerCase().includes(word)
)
) {
return true;
}
return false;
}
private async _shouldRespond(
message: DiscordMessage,
state: State
): Promise<boolean> {
if (message.author.id === this.client.user?.id) return false;
// if (message.author.bot) return false;
if (message.mentions.has(this.client.user?.id as string)) return true;
const guild = message.guild;
const member = guild?.members.cache.get(this.client.user?.id as string);
const nickname = member?.nickname;
if (
message.content
.toLowerCase()
.includes(this.client.user?.username.toLowerCase() as string) ||
message.content
.toLowerCase()
.includes(this.client.user?.tag.toLowerCase() as string) ||
(nickname &&
message.content.toLowerCase().includes(nickname.toLowerCase()))
) {
return true;
}
if (!message.guild) {
return true;
}
// If none of the above conditions are met, use the generateText to decide
const shouldRespondContext = composeContext({
state,
template:
this.runtime.character.templates
?.discordShouldRespondTemplate ||
this.runtime.character.templates?.shouldRespondTemplate ||
discordShouldRespondTemplate,
});
const response = await generateShouldRespond({
runtime: this.runtime,
context: shouldRespondContext,
modelClass: ModelClass.SMALL,
});
if (response === "RESPOND") {
return true;
} else if (response === "IGNORE") {
return false;
} else if (response === "STOP") {
delete this.interestChannels[message.channelId];
return false;
} else {
console.error(
"Invalid response from response generateText:",
response
);
return false;
}
}
private async _generateResponse(
message: Memory,
state: State,
context: string
): Promise<Content> {
const { userId, roomId } = message;
const response = await generateMessageResponse({
runtime: this.runtime,
context,
modelClass: ModelClass.SMALL,
});
if (!response) {
console.error("No response from generateMessageResponse");
return;
}
await this.runtime.databaseAdapter.log({
body: { message, context, response },
userId: userId,
roomId,
type: "response",
});
return response;
}
async fetchBotName(botToken: string) {
const url = "https://discord.com/api/v10/users/@me";
const response = await fetch(url, {
method: "GET",
headers: {
Authorization: `Bot ${botToken}`,
},
});
if (!response.ok) {
throw new Error(
`Error fetching bot details: ${response.statusText}`
);
}
const data = await response.json();
return data.username;
}
}