forked from elizaOS/eliza
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvoice.ts
1122 lines (1002 loc) · 36.1 KB
/
voice.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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
type Content,
type HandlerCallback,
type IAgentRuntime,
type Memory,
ModelClass,
ServiceType,
type State,
type UUID,
composeContext,
composeRandomUser,
elizaLogger,
getEmbeddingZeroVector,
generateMessageResponse,
stringToUuid,
generateShouldRespond,
type ITranscriptionService,
type ISpeechService,
} from "@elizaos/core";
import {
type AudioPlayer,
type AudioReceiveStream,
NoSubscriberBehavior,
StreamType,
type VoiceConnection,
VoiceConnectionStatus,
createAudioPlayer,
createAudioResource,
getVoiceConnections,
joinVoiceChannel,
entersState,
} from "@discordjs/voice";
import {
type BaseGuildVoiceChannel,
ChannelType,
type Client,
type Guild,
type GuildMember,
type VoiceChannel,
type VoiceState,
} from "discord.js";
import EventEmitter from "events";
import prism from "prism-media";
import { type Readable, pipeline } from "stream";
import type { DiscordClient } from "./index.ts";
import {
discordShouldRespondTemplate,
discordVoiceHandlerTemplate,
} from "./templates.ts";
import { getWavHeader } from "./utils.ts";
// These values are chosen for compatibility with picovoice components
const DECODE_FRAME_SIZE = 1024;
const DECODE_SAMPLE_RATE = 16000;
export class AudioMonitor {
private readable: Readable;
private buffers: Buffer[] = [];
private maxSize: number;
private lastFlagged = -1;
private ended = false;
constructor(
readable: Readable,
maxSize: number,
onStart: () => void,
callback: (buffer: Buffer) => void
) {
this.readable = readable;
this.maxSize = maxSize;
this.readable.on("data", (chunk: Buffer) => {
//console.log('AudioMonitor got data');
if (this.lastFlagged < 0) {
this.lastFlagged = this.buffers.length;
}
this.buffers.push(chunk);
const currentSize = this.buffers.reduce(
(acc, cur) => acc + cur.length,
0
);
while (currentSize > this.maxSize) {
this.buffers.shift();
this.lastFlagged--;
}
});
this.readable.on("end", () => {
elizaLogger.log("AudioMonitor ended");
this.ended = true;
if (this.lastFlagged < 0) return;
callback(this.getBufferFromStart());
this.lastFlagged = -1;
});
this.readable.on("speakingStopped", () => {
if (this.ended) return;
elizaLogger.log("Speaking stopped");
if (this.lastFlagged < 0) return;
callback(this.getBufferFromStart());
});
this.readable.on("speakingStarted", () => {
if (this.ended) return;
onStart();
elizaLogger.log("Speaking started");
this.reset();
});
}
stop() {
this.readable.removeAllListeners("data");
this.readable.removeAllListeners("end");
this.readable.removeAllListeners("speakingStopped");
this.readable.removeAllListeners("speakingStarted");
}
isFlagged() {
return this.lastFlagged >= 0;
}
getBufferFromFlag() {
if (this.lastFlagged < 0) {
return null;
}
const buffer = Buffer.concat(this.buffers.slice(this.lastFlagged));
return buffer;
}
getBufferFromStart() {
const buffer = Buffer.concat(this.buffers);
return buffer;
}
reset() {
this.buffers = [];
this.lastFlagged = -1;
}
isEnded() {
return this.ended;
}
}
export class VoiceManager extends EventEmitter {
private processingVoice = false;
private transcriptionTimeout: NodeJS.Timeout | null = null;
private userStates: Map<
string,
{
buffers: Buffer[];
totalLength: number;
lastActive: number;
transcriptionText: string;
}
> = new Map();
private activeAudioPlayer: AudioPlayer | null = null;
private client: Client;
private runtime: IAgentRuntime;
private streams: Map<string, Readable> = new Map();
private connections: Map<string, VoiceConnection> = new Map();
private activeMonitors: Map<
string,
{ channel: BaseGuildVoiceChannel; monitor: AudioMonitor }
> = new Map();
constructor(client: DiscordClient) {
super();
this.client = client.client;
this.runtime = client.runtime;
}
async handleVoiceStateUpdate(oldState: VoiceState, newState: VoiceState) {
const oldChannelId = oldState.channelId;
const newChannelId = newState.channelId;
const member = newState.member;
if (!member) return;
if (member.id === this.client.user?.id) {
return;
}
// Ignore mute/unmute events
if (oldChannelId === newChannelId) {
return;
}
// User leaving a channel where the bot is present
if (oldChannelId && this.connections.has(oldChannelId)) {
this.stopMonitoringMember(member.id);
}
// User joining a channel where the bot is present
if (newChannelId && this.connections.has(newChannelId)) {
await this.monitorMember(
member,
newState.channel as BaseGuildVoiceChannel
);
}
}
async joinChannel(channel: BaseGuildVoiceChannel) {
const oldConnection = this.getVoiceConnection(
channel.guildId as string
);
if (oldConnection) {
try {
oldConnection.destroy();
// Remove all associated streams and monitors
this.streams.clear();
this.activeMonitors.clear();
} catch (error) {
console.error("Error leaving voice channel:", error);
}
}
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator as any,
selfDeaf: false,
selfMute: false,
group: this.client.user.id,
});
try {
// Wait for either Ready or Signalling state
await Promise.race([
entersState(connection, VoiceConnectionStatus.Ready, 20_000),
entersState(
connection,
VoiceConnectionStatus.Signalling,
20_000
),
]);
// Log connection success
elizaLogger.log(
`Voice connection established in state: ${connection.state.status}`
);
// Set up ongoing state change monitoring
connection.on("stateChange", async (oldState, newState) => {
elizaLogger.log(
`Voice connection state changed from ${oldState.status} to ${newState.status}`
);
if (newState.status === VoiceConnectionStatus.Disconnected) {
elizaLogger.log("Handling disconnection...");
try {
// Try to reconnect if disconnected
await Promise.race([
entersState(
connection,
VoiceConnectionStatus.Signalling,
5_000
),
entersState(
connection,
VoiceConnectionStatus.Connecting,
5_000
),
]);
// Seems to be reconnecting to a new channel
elizaLogger.log("Reconnecting to channel...");
} catch (e) {
// Seems to be a real disconnect, destroy and cleanup
elizaLogger.log(
"Disconnection confirmed - cleaning up..." + e
);
try {
connection.destroy();
this.connections.delete(channel.id);
} catch (e2) {
// Seems to be a real disconnect, destroy and cleanup
elizaLogger.log(
"Clean up failed - already closed...", e2
);
}
}
} else if (
newState.status === VoiceConnectionStatus.Destroyed
) {
this.connections.delete(channel.id);
} else if (
!this.connections.has(channel.id) &&
(newState.status === VoiceConnectionStatus.Ready ||
newState.status === VoiceConnectionStatus.Signalling)
) {
this.connections.set(channel.id, connection);
}
});
connection.on("error", (error) => {
elizaLogger.log("Voice connection error:", error);
// Don't immediately destroy - let the state change handler deal with it
elizaLogger.log(
"Connection error - will attempt to recover..."
);
});
// Store the connection
this.connections.set(channel.id, connection);
// Continue with voice state modifications
const me = channel.guild.members.me;
if (me?.voice && me.permissions.has("DeafenMembers")) {
try {
await me.voice.setDeaf(false);
await me.voice.setMute(false);
} catch (error) {
elizaLogger.log("Failed to modify voice state:", error);
// Continue even if this fails
}
}
connection.receiver.speaking.on("start", async (userId: string) => {
let user = channel.members.get(userId);
if (!user) {
try {
user = await channel.guild.members.fetch(userId);
} catch (error) {
console.error("Failed to fetch user:", error);
}
}
if (user && !user?.user.bot) {
this.monitorMember(user as GuildMember, channel);
this.streams.get(userId)?.emit("speakingStarted");
}
});
connection.receiver.speaking.on("end", async (userId: string) => {
const user = channel.members.get(userId);
if (!user?.user.bot) {
this.streams.get(userId)?.emit("speakingStopped");
}
});
} catch (error) {
elizaLogger.log("Failed to establish voice connection:", error);
try {
connection.destroy();
this.connections.delete(channel.id);
} catch (e) {
elizaLogger.log("error cleaning up connect:", e);
}
//throw error;
}
}
private getVoiceConnection(guildId: string) {
const connections = getVoiceConnections(this.client.user.id);
if (!connections) {
return;
}
const connection = [...connections.values()].find(
(connection) => connection.joinConfig.guildId === guildId
);
return connection;
}
private async monitorMember(
member: GuildMember,
channel: BaseGuildVoiceChannel
) {
const userId = member?.id;
const userName = member?.user?.username;
const name = member?.user?.displayName;
const connection = this.getVoiceConnection(member?.guild?.id);
const receiveStream = connection?.receiver.subscribe(userId, {
autoDestroy: true,
emitClose: true,
});
if (!receiveStream || receiveStream.readableLength === 0) {
return;
}
const opusDecoder = new prism.opus.Decoder({
channels: 1,
rate: DECODE_SAMPLE_RATE,
frameSize: DECODE_FRAME_SIZE,
});
const volumeBuffer: number[] = [];
const VOLUME_WINDOW_SIZE = 30;
const SPEAKING_THRESHOLD = 0.05;
opusDecoder.on("data", (pcmData: Buffer) => {
// Monitor the audio volume while the agent is speaking.
// If the average volume of the user's audio exceeds the defined threshold, it indicates active speaking.
// When active speaking is detected, stop the agent's current audio playback to avoid overlap.
if (this.activeAudioPlayer) {
const samples = new Int16Array(
pcmData.buffer,
pcmData.byteOffset,
pcmData.length / 2
);
const maxAmplitude = Math.max(...samples.map(Math.abs)) / 32768;
volumeBuffer.push(maxAmplitude);
if (volumeBuffer.length > VOLUME_WINDOW_SIZE) {
volumeBuffer.shift();
}
const avgVolume =
volumeBuffer.reduce((sum, v) => sum + v, 0) /
VOLUME_WINDOW_SIZE;
if (avgVolume > SPEAKING_THRESHOLD) {
volumeBuffer.length = 0;
this.cleanupAudioPlayer(this.activeAudioPlayer);
this.processingVoice = false;
}
}
});
pipeline(
receiveStream as AudioReceiveStream,
opusDecoder as any,
(err: Error | null) => {
if (err) {
console.log(`Opus decoding pipeline error: ${err}`);
}
}
);
this.streams.set(userId, opusDecoder);
this.connections.set(userId, connection as VoiceConnection);
opusDecoder.on("error", (err: any) => {
console.log(`Opus decoding error: ${err}`);
});
const errorHandler = (err: any) => {
console.log(`Opus decoding error: ${err}`);
};
const streamCloseHandler = () => {
console.log(`voice stream from ${member?.displayName} closed`);
this.streams.delete(userId);
this.connections.delete(userId);
};
const closeHandler = () => {
console.log(`Opus decoder for ${member?.displayName} closed`);
opusDecoder.removeListener("error", errorHandler);
opusDecoder.removeListener("close", closeHandler);
receiveStream?.removeListener("close", streamCloseHandler);
};
opusDecoder.on("error", errorHandler);
opusDecoder.on("close", closeHandler);
receiveStream?.on("close", streamCloseHandler);
this.client.emit(
"userStream",
userId,
name,
userName,
channel,
opusDecoder
);
}
leaveChannel(channel: BaseGuildVoiceChannel) {
const connection = this.connections.get(channel.id);
if (connection) {
try {
connection.destroy();
this.connections.delete(channel.id);
} catch(e) {
elizaLogger.log("Failed to destroy voice connection:", error);
}
}
// Stop monitoring all members in this channel
for (const [memberId, monitorInfo] of this.activeMonitors) {
if (
monitorInfo.channel.id === channel.id &&
memberId !== this.client.user?.id
) {
this.stopMonitoringMember(memberId);
}
}
console.log(`Left voice channel: ${channel.name} (${channel.id})`);
}
stopMonitoringMember(memberId: string) {
const monitorInfo = this.activeMonitors.get(memberId);
if (monitorInfo) {
monitorInfo.monitor.stop();
this.activeMonitors.delete(memberId);
this.streams.delete(memberId);
console.log(`Stopped monitoring user ${memberId}`);
}
}
async handleGuildCreate(guild: Guild) {
console.log(`Joined guild ${guild.name}`);
// this.scanGuild(guild);
}
async debouncedProcessTranscription(
userId: UUID,
name: string,
userName: string,
channel: BaseGuildVoiceChannel
) {
const DEBOUNCE_TRANSCRIPTION_THRESHOLD = 1500; // wait for 1.5 seconds of silence
if (this.activeAudioPlayer?.state?.status === "idle") {
elizaLogger.log("Cleaning up idle audio player.");
this.cleanupAudioPlayer(this.activeAudioPlayer);
}
if (this.activeAudioPlayer || this.processingVoice) {
const state = this.userStates.get(userId);
state.buffers.length = 0;
state.totalLength = 0;
return;
}
if (this.transcriptionTimeout) {
clearTimeout(this.transcriptionTimeout);
}
this.transcriptionTimeout = setTimeout(async () => {
this.processingVoice = true;
try {
await this.processTranscription(
userId,
channel.id,
channel,
name,
userName
);
// Clean all users' previous buffers
this.userStates.forEach((state, _) => {
state.buffers.length = 0;
state.totalLength = 0;
});
} finally {
this.processingVoice = false;
}
}, DEBOUNCE_TRANSCRIPTION_THRESHOLD);
}
async handleUserStream(
userId: UUID,
name: string,
userName: string,
channel: BaseGuildVoiceChannel,
audioStream: Readable
) {
console.log(`Starting audio monitor for user: ${userId}`);
if (!this.userStates.has(userId)) {
this.userStates.set(userId, {
buffers: [],
totalLength: 0,
lastActive: Date.now(),
transcriptionText: "",
});
}
const state = this.userStates.get(userId);
const processBuffer = async (buffer: Buffer) => {
try {
state!.buffers.push(buffer);
state!.totalLength += buffer.length;
state!.lastActive = Date.now();
this.debouncedProcessTranscription(
userId,
name,
userName,
channel
);
} catch (error) {
console.error(
`Error processing buffer for user ${userId}:`,
error
);
}
};
new AudioMonitor(
audioStream,
10000000,
() => {
if (this.transcriptionTimeout) {
clearTimeout(this.transcriptionTimeout);
}
},
async (buffer) => {
if (!buffer) {
console.error("Received empty buffer");
return;
}
await processBuffer(buffer);
}
);
}
private async processTranscription(
userId: UUID,
channelId: string,
channel: BaseGuildVoiceChannel,
name: string,
userName: string
) {
const state = this.userStates.get(userId);
if (!state || state.buffers.length === 0) return;
try {
const inputBuffer = Buffer.concat(state.buffers, state.totalLength);
state.buffers.length = 0; // Clear the buffers
state.totalLength = 0;
// Convert Opus to WAV
const wavBuffer = await this.convertOpusToWav(inputBuffer);
console.log("Starting transcription...");
const transcriptionText = await this.runtime
.getService<ITranscriptionService>(ServiceType.TRANSCRIPTION)
.transcribe(wavBuffer);
function isValidTranscription(text: string): boolean {
if (!text || text.includes("[BLANK_AUDIO]")) return false;
return true;
}
if (transcriptionText && isValidTranscription(transcriptionText)) {
state.transcriptionText += transcriptionText;
}
if (state.transcriptionText.length) {
this.cleanupAudioPlayer(this.activeAudioPlayer);
const finalText = state.transcriptionText;
state.transcriptionText = "";
await this.handleUserMessage(
finalText,
userId,
channelId,
channel,
name,
userName
);
}
} catch (error) {
console.error(
`Error transcribing audio for user ${userId}:`,
error
);
}
}
private async handleUserMessage(
message: string,
userId: UUID,
channelId: string,
channel: BaseGuildVoiceChannel,
name: string,
userName: string
) {
try {
const roomId = stringToUuid(channelId + "-" + this.runtime.agentId);
const userIdUUID = stringToUuid(userId);
await this.runtime.ensureConnection(
userIdUUID,
roomId,
userName,
name,
"discord"
);
let state = await this.runtime.composeState(
{
agentId: this.runtime.agentId,
content: { text: message, source: "Discord" },
userId: userIdUUID,
roomId,
},
{
discordChannel: channel,
discordClient: this.client,
agentName: this.runtime.character.name,
}
);
if (message && message.startsWith("/")) {
return null;
}
const memory = {
id: stringToUuid(channelId + "-voice-message-" + Date.now()),
agentId: this.runtime.agentId,
content: {
text: message,
source: "discord",
url: channel.url,
},
userId: userIdUUID,
roomId,
embedding: getEmbeddingZeroVector(),
createdAt: Date.now(),
};
if (!memory.content.text) {
return { text: "", action: "IGNORE" };
}
await this.runtime.messageManager.createMemory(memory);
state = await this.runtime.updateRecentMessageState(state);
const shouldIgnore = await this._shouldIgnore(memory);
if (shouldIgnore) {
return { text: "", action: "IGNORE" };
}
const shouldRespond = await this._shouldRespond(
message,
userId,
channel,
state
);
if (!shouldRespond) {
return;
}
const context = composeContext({
state,
template:
this.runtime.character.templates
?.discordVoiceHandlerTemplate ||
this.runtime.character.templates?.messageHandlerTemplate ||
discordVoiceHandlerTemplate,
});
const responseContent = await this._generateResponse(
memory,
state,
context
);
const callback: HandlerCallback = async (content: Content) => {
console.log("callback content: ", content);
const { roomId } = memory;
const responseMemory: Memory = {
id: stringToUuid(
memory.id + "-voice-response-" + Date.now()
),
agentId: this.runtime.agentId,
userId: this.runtime.agentId,
content: {
...content,
user: this.runtime.character.name,
inReplyTo: memory.id,
},
roomId,
embedding: getEmbeddingZeroVector(),
};
if (responseMemory.content.text?.trim()) {
await this.runtime.messageManager.createMemory(
responseMemory
);
state = await this.runtime.updateRecentMessageState(state);
const responseStream = await this.runtime
.getService<ISpeechService>(
ServiceType.SPEECH_GENERATION
)
.generate(this.runtime, content.text);
if (responseStream) {
await this.playAudioStream(
userId,
responseStream as Readable
);
}
await this.runtime.evaluate(memory, state);
} else {
console.warn("Empty response, skipping");
}
return [responseMemory];
};
const responseMemories = await callback(responseContent);
const response = responseContent;
const content = (response.responseMessage ||
response.content ||
response.message) as string;
if (!content) {
return null;
}
console.log("responseMemories: ", responseMemories);
await this.runtime.processActions(
memory,
responseMemories,
state,
callback
);
} catch (error) {
console.error("Error processing transcribed text:", error);
}
}
private async convertOpusToWav(pcmBuffer: Buffer): Promise<Buffer> {
try {
// Generate the WAV header
const wavHeader = getWavHeader(
pcmBuffer.length,
DECODE_SAMPLE_RATE
);
// Concatenate the WAV header and PCM data
const wavBuffer = Buffer.concat([wavHeader, pcmBuffer]);
return wavBuffer;
} catch (error) {
console.error("Error converting PCM to WAV:", error);
throw error;
}
}
private async _shouldRespond(
message: string,
userId: UUID,
channel: BaseGuildVoiceChannel,
state: State
): Promise<boolean> {
if (userId === this.client.user?.id) return false;
const lowerMessage = message.toLowerCase();
const botName = this.client.user.username.toLowerCase();
const characterName = this.runtime.character.name.toLowerCase();
const guild = channel.guild;
const member = guild?.members.cache.get(this.client.user?.id as string);
const nickname = member?.nickname;
if (
lowerMessage.includes(botName as string) ||
lowerMessage.includes(characterName) ||
lowerMessage.includes(
this.client.user?.tag.toLowerCase() as string
) ||
(nickname && lowerMessage.includes(nickname.toLowerCase()))
) {
return true;
}
if (!channel.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 ||
composeRandomUser(discordShouldRespondTemplate, 2),
});
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") {
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.LARGE,
});
response.source = "discord";
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;
}
private async _shouldIgnore(message: Memory): Promise<boolean> {
// console.log("message: ", message);
elizaLogger.debug("message.content: ", message.content);
// if the message is 3 characters or less, ignore it
if ((message.content as Content).text.length < 3) {
return true;
}
const loseInterestWords = [
// telling the bot to stop talking
"shut up",
"stop",
"dont talk",
"silence",
"stop talking",
"be quiet",
"hush",
"stfu",
"stupid bot",
"dumb bot",
// offensive words
"fuck",
"shit",
"damn",
"suck",
"dick",
"cock",
"sex",
"sexy",
];
if (
(message.content as Content).text.length < 50 &&
loseInterestWords.some((word) =>
(message.content as Content).text?.toLowerCase().includes(word)
)
) {
return true;
}
const ignoreWords = ["k", "ok", "bye", "lol", "nm", "uh"];
if (
(message.content as Content).text?.length < 8 &&
ignoreWords.some((word) =>
(message.content as Content).text?.toLowerCase().includes(word)
)
) {
return true;
}
return false;
}
async scanGuild(guild: Guild) {
let chosenChannel: BaseGuildVoiceChannel | null = null;
try {
const channelId = this.runtime.getSetting(
"DISCORD_VOICE_CHANNEL_ID"
) as string;
if (channelId) {
const channel = await guild.channels.fetch(channelId);
if (channel?.isVoiceBased()) {
chosenChannel = channel as BaseGuildVoiceChannel;
}
}
if (!chosenChannel) {
const channels = (await guild.channels.fetch()).filter(
(channel) => channel?.type == ChannelType.GuildVoice
);
for (const [, channel] of channels) {
const voiceChannel = channel as BaseGuildVoiceChannel;
if (
voiceChannel.members.size > 0 &&
(chosenChannel === null ||
voiceChannel.members.size >
chosenChannel.members.size)
) {
chosenChannel = voiceChannel;
}
}
}
if (chosenChannel) {
console.log(`Joining channel: ${chosenChannel.name}`);
await this.joinChannel(chosenChannel);
} else {