-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.js
2831 lines (2495 loc) · 102 KB
/
index.js
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 dotenv from 'dotenv';
dotenv.config();
import {
Client,
GatewayIntentBits,
Partials,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
TextInputBuilder,
TextInputStyle,
ModalBuilder,
PermissionsBitField,
EmbedBuilder,
AttachmentBuilder,
ActivityType,
StringSelectMenuBuilder,
ComponentType,
REST,
Routes,
} from 'discord.js';
import {
GoogleGenerativeAI,
HarmBlockThreshold,
HarmCategory
} from '@google/generative-ai';
import { GoogleAIFileManager, FileState } from '@google/generative-ai/server';
import { writeFile, unlink } from 'fs/promises';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { getTextExtractor } from 'office-text-extractor'
import * as cheerio from 'cheerio';
import osu from 'node-os-utils';
const { mem } = osu;
const { cpu } = osu;
import axios from 'axios';
const config = JSON.parse(fs.readFileSync('config.json', 'utf-8'));
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages,
],
partials: [Partials.Channel],
});
const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY);
const fileManager = new GoogleAIFileManager(process.env.GOOGLE_API_KEY);
const token = process.env.DISCORD_BOT_TOKEN;
const activeRequests = new Set();
// Define your objects
let chatHistories = {};
let activeUsersInChannels = {};
let customInstructions = {};
let serverSettings = {};
let userPreferredImageModel = {};
let userPreferredImageResolution = {};
let userPreferredImagePromptEnhancement = {};
let userPreferredSpeechModel = {};
let userResponsePreference = {};
let alwaysRespondChannels = {};
let channelWideChatHistory = {};
let blacklistedUsers = {};
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const CONFIG_DIR = path.join(__dirname, 'config');
const CHAT_HISTORIES_DIR = path.join(CONFIG_DIR, 'chat_histories_3');
const FILE_PATHS = {
activeUsersInChannels: path.join(CONFIG_DIR, 'active_users_in_channels.json'),
customInstructions: path.join(CONFIG_DIR, 'custom_instructions.json'),
serverSettings: path.join(CONFIG_DIR, 'server_settings.json'),
userPreferredImageModel: path.join(CONFIG_DIR, 'user_preferred_image_model.json'),
userPreferredImageResolution: path.join(CONFIG_DIR, 'user_preferred_image_resolution.json'),
userPreferredImagePromptEnhancement: path.join(CONFIG_DIR, 'user_preferred_image_prompt_enhancement.json'),
userPreferredSpeechModel: path.join(CONFIG_DIR, 'user_preferred_speech_model.json'),
userResponsePreference: path.join(CONFIG_DIR, 'user_response_preference.json'),
alwaysRespondChannels: path.join(CONFIG_DIR, 'always_respond_channels.json'),
channelWideChatHistory: path.join(CONFIG_DIR, 'channel_wide_chatistory.json'),
blacklistedUsers: path.join(CONFIG_DIR, 'blacklisted_users.json')
};
function saveStateToFile() {
try {
if (!fs.existsSync(CONFIG_DIR)) {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
if (!fs.existsSync(CHAT_HISTORIES_DIR)) {
fs.mkdirSync(CHAT_HISTORIES_DIR, { recursive: true });
}
for (let [key, value] of Object.entries(chatHistories)) {
fs.writeFileSync(path.join(CHAT_HISTORIES_DIR, `${key}.json`), JSON.stringify(value, null, 2), 'utf-8');
}
for (let [key, value] of Object.entries(FILE_PATHS)) {
fs.writeFileSync(value, JSON.stringify(eval(key), null, 2), 'utf-8');
}
} catch (error) {
console.error('Error saving state to files:', error);
}
}
function loadStateFromFile() {
try {
if (!fs.existsSync(CONFIG_DIR)) {
console.warn('Config directory does not exist. Initializing with empty state.');
return;
}
if (!fs.existsSync(CHAT_HISTORIES_DIR)) {
fs.mkdirSync(CHAT_HISTORIES_DIR, { recursive: true });
} else {
fs.readdirSync(CHAT_HISTORIES_DIR).forEach(file => {
if (file.endsWith('.json')) {
const user = path.basename(file, '.json');
try {
const data = fs.readFileSync(path.join(CHAT_HISTORIES_DIR, file), 'utf-8');
chatHistories[user] = JSON.parse(data);
} catch (readError) {
console.error(`Error reading chat history for ${user}:`, readError);
}
}
});
}
for (let [key, value] of Object.entries(FILE_PATHS)) {
if (fs.existsSync(value)) {
try {
const data = fs.readFileSync(value, 'utf-8');
eval(`${key} = JSON.parse(data)`);
} catch (readError) {
console.error(`Error reading ${key}:`, readError);
}
}
}
} catch (error) {
console.error('Error loading state from files:', error);
}
}
function removeFileData(chatHistories) {
try {
Object.values(chatHistories).forEach(subIdEntries => {
subIdEntries.forEach(message => {
if (message.content) {
message.content = message.content.filter(contentItem => {
if (contentItem.fileData) {
delete contentItem.fileData;
}
return Object.keys(contentItem).length > 0;
});
}
});
});
console.log('fileData elements have been removed from chat histories.');
} catch (error) {
console.error('An error occurred while removing fileData elements:', error);
}
}
function scheduleDailyReset() {
try {
const now = new Date();
const nextReset = new Date();
nextReset.setHours(0, 0, 0, 0);
if (nextReset <= now) {
nextReset.setDate(now.getDate() + 1);
}
const timeUntilNextReset = nextReset - now;
setTimeout(() => {
removeFileData(chatHistories);
scheduleDailyReset();
}, timeUntilNextReset);
} catch (error) {
console.error('An error occurred while scheduling the daily reset:', error);
}
}
scheduleDailyReset();
loadStateFromFile();
// <=====[Configuration]=====>
const MODEL = "gemini-1.5-flash-latest";
/*
`BLOCK_NONE` - Always show regardless of probability of unsafe content
`BLOCK_ONLY_HIGH` - Block when high probability of unsafe content
`BLOCK_MEDIUM_AND_ABOVE` - Block when medium or high probability of unsafe content
`BLOCK_LOW_AND_ABOVE` - Block when low, medium or high probability of unsafe content
`HARM_BLOCK_THRESHOLD_UNSPECIFIED` - Threshold is unspecified, block using default threshold
*/
const safetySettings = [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
{
category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold: HarmBlockThreshold.BLOCK_NONE,
},
];
const generationConfig = {
temperature: 1.0
};
const defaultResponseFormat = config.defaultResponseFormat;
const defaultImgModel = config.defaultImgModel;
const hexColour = config.hexColour;
const activities = config.activities.map(activity => ({
name: activity.name,
type: ActivityType[activity.type]
}));
const defaultPersonality = config.defaultPersonality;
const defaultServerSettings = config.defaultServerSettings;
const workInDMs = config.workInDMs;
const shouldDisplayPersonalityButtons = config.shouldDisplayPersonalityButtons;
const SEND_RETRY_ERRORS_TO_DISCORD = config.SEND_RETRY_ERRORS_TO_DISCORD;
import {
speechGen,
musicGen,
generateWithPlayground,
generateImage,
generateWithDalle3,
imgModels,
imageModelFunctions
} from './tools/generators.js';
import { function_declarations, manageToolCall, processFunctionCallsNames } from './tools/function_calling.js';
import {
delay,
retryOperation,
filterPrompt,
enhancePrompt
} from './tools/others.js';
// <==========>
// <=====[Register Commands And Activities]=====>
import { commands } from './commands.js';
let activityIndex = 0;
client.once('ready', async () => {
console.log(`Logged in as ${client.user.tag}!`);
const rest = new REST({ version: '10' }).setToken(token);
try {
console.log('Started refreshing application (/) commands.');
await rest.put(
Routes.applicationCommands(client.user.id), { body: commands },
);
console.log('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
}
client.user.setPresence({
activities: [activities[activityIndex]],
status: 'idle',
});
setInterval(() => {
activityIndex = (activityIndex + 1) % activities.length;
client.user.setPresence({
activities: [activities[activityIndex]],
status: 'idle',
});
}, 30000);
});
// <==========>
// <=====[Messages And Interaction]=====>
client.on('messageCreate', async (message) => {
try {
if (message.author.bot) return;
if (message.content.startsWith('!')) return;
const isDM = message.channel.type === ChannelType.DM;
const mentionPattern = new RegExp(`^<@!?${client.user.id}>(?:\\s+)?(generate|imagine)`, 'i');
const startsWithPattern = /^generate|^imagine/i;
const command = message.content.match(mentionPattern) || message.content.match(startsWithPattern);
const shouldRespond = (
workInDMs && isDM ||
alwaysRespondChannels[message.channelId] ||
(message.mentions.users.has(client.user.id) && !isDM) ||
activeUsersInChannels[message.channelId]?.[message.author.id]
);
if (shouldRespond) {
if (message.guild) {
initializeBlacklistForGuild(message.guild.id);
if (blacklistedUsers[message.guild.id].includes(message.author.id)) {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Blacklisted')
.setDescription('You are blacklisted and cannot use this bot.');
return message.reply({ embeds: [embed] });
}
}
if (command) {
const prompt = message.content.slice(command.index + command[0].length).trim();
if (prompt) {
await genimg(prompt, message);
} else {
const embed = new EmbedBuilder()
.setColor(0x00FFFF)
.setTitle('Invalid Prompt')
.setDescription('Please provide a valid prompt.');
await message.channel.send({ embeds: [embed] });
}
} else if (activeRequests.has(message.author.id)) {
const embed = new EmbedBuilder()
.setColor(0xFFFF00)
.setTitle('Request In Progress')
.setDescription('Please wait until your previous action is complete.');
await message.reply({ embeds: [embed] });
} else {
await handleTextMessage(message);
}
}
} catch (error) {
console.error('Error processing the message:', error);
if (activeRequests.has(message.author.id)) {
activeRequests.delete(message.author.id);
}
}
});
client.on('interactionCreate', async (interaction) => {
try {
if (interaction.isCommand()) {
await handleCommandInteraction(interaction);
} else if (interaction.isButton()) {
await handleButtonInteraction(interaction);
} else if (interaction.isModalSubmit()) {
await handleModalSubmit(interaction);
} else if (interaction.isStringSelectMenu()) {
await handleSelectMenuInteraction(interaction);
}
} catch (error) {
console.error('Error handling interaction:', error.message);
}
});
async function handleCommandInteraction(interaction) {
if (!interaction.isCommand()) return;
const commandHandlers = {
respond_to_all: handleRespondToAllCommand,
toggle_channel_chat_history: toggleChannelChatHistory,
whitelist: handleWhitelistCommand,
blacklist: handleBlacklistCommand,
imagine: handleImagineCommand,
clear_memory: handleClearMemoryCommand,
speech: handleSpeechCommand,
settings: showSettings,
server_settings: showDashboard,
music: handleMusicCommand,
status: handleStatusCommand
};
const handler = commandHandlers[interaction.commandName];
if (handler) {
await handler(interaction);
} else {
console.log(`Unknown command: ${interaction.commandName}`);
}
}
async function handleButtonInteraction(interaction) {
if (!interaction.isButton()) return;
if (interaction.guild) {
initializeBlacklistForGuild(interaction.guild.id);
if (blacklistedUsers[interaction.guild.id].includes(interaction.user.id)) {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Blacklisted')
.setDescription('You are blacklisted and cannot use this interaction.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
}
const buttonHandlers = {
'server-chat-history': toggleServerWideChatHistory,
'clear-server': clearServerChatHistory,
'settings-save-buttons': toggleSettingSaveButton,
'custom-server-personality': serverPersonality,
'toggle-server-personality': toggleServerPersonality,
'download-server-conversation': downloadServerConversation,
'response-server-mode': toggleServerPreference,
'toggle-response-server-mode': toggleServerResponsePreference,
'settings': showSettings,
'back_to_main_settings': editShowSettings,
'clear-memory': handleClearMemoryCommand,
'always-respond': alwaysRespond,
'custom-personality': handleCustomPersonalityCommand,
'remove-personality': handleRemovePersonalityCommand,
'generate-image': handleGenerateImageButton,
'change-image-model': changeImageModel,
'toggle-prompt-enhancer': togglePromptEnhancer,
'change-image-resolution': changeImageResolution,
'toggle-response-mode': handleToggleResponseMode,
'generate-speech': processSpeechGet,
'generate-music': processMusicGet,
'change-speech-model': changeSpeechModel,
'download-conversation': downloadConversation,
'download_message': downloadMessage,
'general-settings': handleSubButtonInteraction,
'image-settings': handleSubButtonInteraction,
'speech-settings': handleSubButtonInteraction,
'music-settings': handleSubButtonInteraction,
};
for (const [key, handler] of Object.entries(buttonHandlers)) {
if (interaction.customId.startsWith(key)) {
if (key === 'select-speech-model-') {
const selectedModel = interaction.customId.replace('select-speech-model-', '');
await handleSpeechSelectModel(interaction, selectedModel);
} else {
await handler(interaction);
}
return;
}
}
if (interaction.customId.startsWith('delete_message-')) {
const msgId = interaction.customId.replace('delete_message-', '');
await handleDeleteMessageInteraction(interaction, msgId);
}
}
async function handleDeleteMessageInteraction(interaction, msgId) {
const userId = interaction.user.id;
const userChatHistory = chatHistories[userId];
const channel = interaction.channel;
const message = channel ? (await channel.messages.fetch(msgId).catch(() => false)) : false;
if (userChatHistory) {
if (userChatHistory[msgId]) {
delete userChatHistory[msgId];
await deleteMsg();
} else {
try {
const replyingTo = message ? (message.reference ? (await message.channel.messages.fetch(message.reference.messageId)).author.id : 0) : 0;
if (userId === replyingTo) {
await deleteMsg();
} else {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Not For You')
.setDescription('This button is not meant for you.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
} catch (error) {}
}
}
async function deleteMsg() {
await interaction.message.delete()
.catch('Error deleting interaction message: ', console.error);
if (channel) {
if (message) {
message.delete().catch(() => {});
}
}
}
}
async function handleSelectMenuInteraction(interaction) {
if (!interaction.isStringSelectMenu()) return;
const selectMenuHandlers = {
'select-image-model': handleImageSelectModel,
'select-image-resolution': handleImageSelectResolution
};
const handler = selectMenuHandlers[interaction.customId];
if (handler) {
const selectedValue = interaction.values[0];
await handler(interaction, selectedValue);
}
}
async function handleClearMemoryCommand(interaction) {
const serverChatHistoryEnabled = interaction.guild ? serverSettings[interaction.guild.id]?.serverChatHistory : false;
if (!serverChatHistoryEnabled) {
await clearChatHistory(interaction);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF5555)
.setTitle('Feature Disabled')
.setDescription('Clearing chat history is not enabled for this server, Server-Wide chat history is active.');
await interaction.reply({ embeds: [embed] });
}
}
async function handleCustomPersonalityCommand(interaction) {
const serverCustomEnabled = interaction.guild ? serverSettings[interaction.guild.id]?.customServerPersonality : false;
if (!serverCustomEnabled) {
await setCustomPersonality(interaction);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF5555)
.setTitle('Feature Disabled')
.setDescription('Custom personality is not enabled for this server, Server-Wide personality is active.');
await interaction.reply({ embeds: [embed], ephemeral: true });
}
}
async function handleRemovePersonalityCommand(interaction) {
const isServerEnabled = interaction.guild ? serverSettings[interaction.guild.id]?.customServerPersonality : false;
if (!isServerEnabled) {
await removeCustomPersonality(interaction);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF5555)
.setTitle('Feature Disabled')
.setDescription('Custom personality is not enabled for this server, Server-Wide personality is active.');
await interaction.reply({ embeds: [embed], ephemeral: true });
}
}
async function handleToggleResponseMode(interaction) {
const serverResponsePreferenceEnabled = interaction.guild ? serverSettings[interaction.guild.id]?.serverResponsePreference : false;
if (!serverResponsePreferenceEnabled) {
await toggleUserResponsePreference(interaction);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF5555)
.setTitle('Feature Disabled')
.setDescription('Toggling Response Mode is not enabled for this server, Server-Wide Response Mode is active.');
await interaction.reply({ embeds: [embed], ephemeral: true });
}
}
async function editShowSettings(interaction) {
await showSettings(interaction, true);
}
// <==========>
// <=====[Messages Handling]=====>
async function handleTextMessage(message) {
const botId = client.user.id;
const userId = message.author.id;
const guildId = message.guild?.id;
const channelId = message.channel.id;
let messageContent = message.content.replace(new RegExp(`<@!?${botId}>`), '').trim();
if (messageContent === '' && !(message.attachments.size > 0 && hasSupportedAttachments(message))) {
const embed = new EmbedBuilder()
.setColor(0x00FFFF)
.setTitle('Empty Message')
.setDescription("It looks like you didn't say anything. What would you like to talk about?");
const botMessage = await message.reply({ embeds: [embed] });
await addSettingsButton(botMessage);
return;
}
message.channel.sendTyping();
const typingInterval = setInterval(() => {
message.channel.sendTyping();
}, 4000);
setTimeout(() => {
clearInterval(typingInterval);
}, 120000);
let botMessage = false;
let parts;
try {
if (SEND_RETRY_ERRORS_TO_DISCORD) {
clearInterval(typingInterval);
const updateEmbedDescription = (textAttachmentStatus, imageAttachmentStatus, finalText) => {
return `Let me think...\n\n- ${textAttachmentStatus}: Text Attachment Check\n- ${imageAttachmentStatus}: Media Attachment Check\n${finalText || ''}`;
};
const embed = new EmbedBuilder()
.setColor(0x00FFFF)
.setTitle('Processing')
.setDescription(updateEmbedDescription('[🔁]', '[🔁]'));
botMessage = await message.reply({ embeds: [embed] });
messageContent = await extractFileText(message, messageContent);
embed.setDescription(updateEmbedDescription('[☑️]', '[🔁]'));
await botMessage.edit({ embeds: [embed] });
parts = await processPromptAndMediaAttachments(messageContent, message);
embed.setDescription(updateEmbedDescription('[☑️]', '[☑️]', '### All checks done. Waiting for the response...'));
await botMessage.edit({ embeds: [embed] });
} else {
messageContent = await extractFileText(message, messageContent);
parts = await processPromptAndMediaAttachments(messageContent, message);
}
} catch (error) {
return console.error('Error initialising message', error);
}
let instructions;
if (guildId) {
if (channelWideChatHistory[channelId]) {
instructions = customInstructions[channelId];
} else if (serverSettings[guildId]?.customServerPersonality && customInstructions[guildId]) {
instructions = customInstructions[guildId];
} else {
instructions = customInstructions[userId];
}
} else {
instructions = customInstructions[userId];
}
activeRequests.add(userId);
let infoStr = '';
if (guildId) {
const userInfo = {
username: message.author.username,
displayName: message.author.displayName
};
infoStr = `\nYou are currently engaging with users in the ${message.guild.name} Discord server.\n\n## Current User Information\nUsername: \`${userInfo.username}\`\nDisplay Name: \`${userInfo.displayName}\``;
}
const isServerChatHistoryEnabled = guildId ? serverSettings[guildId]?.serverChatHistory : false;
const isChannelChatHistoryEnabled = guildId ? channelWideChatHistory[channelId] : false;
const finalInstructions = isServerChatHistoryEnabled ? instructions + infoStr : instructions;
const historyId = isChannelChatHistoryEnabled ? (isServerChatHistoryEnabled ? guildId : channelId) : userId;
const model = await genAI.getGenerativeModel({
model: MODEL,
systemInstruction: { role: "system", parts: [{ text: finalInstructions || defaultPersonality }] },
generationConfig,
tools: { functionDeclarations: function_declarations }
});
const chat = model.startChat({
history: getHistory(historyId),
safetySettings,
});
await handleModelResponse(botMessage, chat, parts, message, typingInterval, historyId);
}
function hasSupportedAttachments(message) {
const supportedFileExtensions = [ '.html', '.js', '.css', '.json', '.xml', '.csv', '.py', '.java', '.sql', '.log', '.md', '.txt', '.pdf', '.docx' ];
return message.attachments.some((attachment) => {
const contentType = (attachment.contentType || "").toLowerCase();
const fileExtension = path.extname(attachment.name) || '';
return (
(contentType.startsWith('image/') && contentType !== 'image/gif') ||
contentType.startsWith('audio/') ||
contentType.startsWith('video/') ||
supportedFileExtensions.includes(fileExtension)
);
});
}
async function downloadFile(url, filePath) {
const writer = fs.createWriteStream(filePath);
const response = await axios({
url,
method: 'GET',
responseType: 'stream',
});
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', resolve);
writer.on('error', reject);
});
}
function sanitizeFileName(fileName) {
return fileName
.toLowerCase()
.replace(/[^a-z0-9-]/g, '-') // replace non-lowercase alphanumeric and dashes with dashes
.replace(/^-+|-+$/g, ''); // remove leading and trailing dashes
}
async function processPromptAndMediaAttachments(prompt, message) {
const attachments = JSON.parse(JSON.stringify(Array.from(message.attachments.values())));
let parts = [{ text: prompt }];
if (attachments.length > 0) {
const validAttachments = attachments.filter(
(attachment) => {
const contentType = attachment.contentType.toLowerCase();
return (contentType.startsWith('image/') && contentType !== 'image/gif') ||
contentType.startsWith('audio/') ||
contentType.startsWith('video/');
}
);
if (validAttachments.length > 0) {
const attachmentParts = await Promise.all(
validAttachments.map(async (attachment) => {
const sanitizedFileName = sanitizeFileName(attachment.name);
const filePath = path.join(__dirname, sanitizedFileName);
try {
// Download the file
await downloadFile(attachment.url, filePath);
// Upload the downloaded file
const uploadResult = await fileManager.uploadFile(filePath, {
mimeType: attachment.contentType,
displayName: sanitizedFileName,
});
const name = uploadResult.file.name;
if (name === null) {
throw new Error(`Unable to extract file name from upload result: ${nameField}`);
}
// Check if the file is a video and wait for its state to be 'ACTIVE'
if (attachment.contentType.startsWith('video/')) {
let file = await fileManager.getFile(name);
while (file.state === FileState.PROCESSING) {
process.stdout.write(".");
await new Promise((resolve) => setTimeout(resolve, 10_000));
file = await fileManager.getFile(name);
}
if (file.state === FileState.FAILED) {
throw new Error(`Video processing failed for ${sanitizedFileName}.`);
}
}
// Delete the local file
fs.unlinkSync(filePath);
return {
fileData: {
mimeType: attachment.contentType,
fileUri: uploadResult.file.uri,
},
};
} catch (error) {
console.error(`Error processing attachment ${sanitizedFileName}:`, error);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
return null;
}
})
);
parts = [...parts, ...attachmentParts.filter(part => part !== null)];
}
}
return parts;
}
async function extractFileText(message, messageContent) {
if (message.attachments.size > 0) {
let attachments = Array.from(message.attachments.values());
for (const attachment of attachments) {
const fileType = path.extname(attachment.name) || '';
const fileTypes = [ '.html', '.js', '.css', '.json', '.xml', '.csv', '.py', '.java', '.sql', '.log', '.md', '.txt', '.pdf', '.docx' ];
if (fileTypes.includes(fileType)) {
try {
let fileContent = await downloadAndReadFile(attachment.url, fileType);
messageContent += `\n\n[\`${attachment.name}\` File Content]:\n\`\`\`\n${fileContent}\n\`\`\``;
} catch (error) {
console.error(`Error reading file ${attachment.name}: ${error.message}`);
}
}
}
}
return messageContent;
}
async function downloadAndReadFile(url, fileType) {
let response = await fetch(url);
if (!response.ok) throw new Error(`Failed to download ${response.statusText}`);
switch (fileType) {
case 'pdf':
case 'docx':
let buffer = await response.arrayBuffer();
const extractor = getTextExtractor();
return (await extractor.extractText({ input: buffer, type: 'buffer' }));
default:
return await response.text();
}
}
// <==========>
// <=====[Interaction Reply 1 (Image And Speech Gen)]=====>
async function handleImagineCommand(interaction) {
try {
if (!workInDMs && interaction.channel.type === ChannelType.DM) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('DMs Disabled')
.setDescription('DM interactions are disabled for this bot.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
if (interaction.guild) {
initializeBlacklistForGuild(interaction.guild.id);
if (blacklistedUsers[interaction.guild.id].includes(interaction.user.id)) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('Blacklisted')
.setDescription('You are blacklisted and cannot use this interaction.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
}
const prompt = interaction.options.getString('prompt');
const model = interaction.options.getString('model');
const resolution = interaction.options.getString('resolution');
if (resolution) {
userPreferredImageResolution[interaction.user.id] = resolution;
}
await genimgslash(prompt, model, interaction);
} catch (error) {
console.log(error.message);
}
}
async function handleSpeechCommand(interaction) {
try {
if (!workInDMs && interaction.channel.type === ChannelType.DM) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('DMs Disabled')
.setDescription('DM interactions are disabled for this bot.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
if (interaction.guild) {
initializeBlacklistForGuild(interaction.guild.id);
if (blacklistedUsers[interaction.guild.id].includes(interaction.user.id)) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('Blacklisted')
.setDescription('You are blacklisted and cannot use this interaction.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
}
const embed = new EmbedBuilder()
.setColor(0x00FFFF)
.setTitle('Generating Speech')
.setDescription(`Generating your speech, please wait... 💽`);
await interaction.reply({ embeds: [embed], ephemeral: true });
const userId = interaction.user.id;
const text = interaction.options.getString('prompt');
const language = interaction.options.getString('language');
const outputUrl = await generateSpeechWithPrompt(text, userId, language);
if (outputUrl && outputUrl !== 'Output URL is not available.') {
await handleSuccessfulSpeechGeneration(interaction, text, language, outputUrl);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Error')
.setDescription(`Sorry, something went wrong, or the output URL is not available.\n> **Text:**\n\`\`\`\n${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\n\`\`\``);
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed] });
await addSettingsButton(messageReference);
}
} catch (error) {
console.log(error);
try {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Error')
.setDescription(`Sorry, something went wrong and the output is not available.\n> **Text:**\n\`\`\`\n${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\n\`\`\``);
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed] });
await addSettingsButton(messageReference);
} catch (error) {}
}
}
async function handleMusicCommand(interaction) {
try {
if (!workInDMs && interaction.channel.type === ChannelType.DM) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('DMs Disabled')
.setDescription('DM interactions are disabled for this bot.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
if (interaction.guild) {
initializeBlacklistForGuild(interaction.guild.id);
if (blacklistedUsers[interaction.guild.id].includes(interaction.user.id)) {
const embed = new EmbedBuilder()
.setColor(hexColour)
.setTitle('Blacklisted')
.setDescription('You are blacklisted and cannot use this interaction.');
return interaction.reply({ embeds: [embed], ephemeral: true });
}
}
const embed = new EmbedBuilder()
.setColor(0x00FFFF)
.setTitle('Generating Music')
.setDescription(`Generating your music, please wait... 🎧`);
await interaction.reply({ embeds: [embed], ephemeral: true });
const userId = interaction.user.id;
const text = interaction.options.getString('prompt');
const outputUrl = await generateMusicWithPrompt(text, userId);
if (outputUrl && outputUrl !== 'Output URL is not available.') {
await handleSuccessfulMusicGeneration(interaction, text, outputUrl);
} else {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Error')
.setDescription(`Sorry, something went wrong, or the output URL is not available.\n> **Text:**\n\`\`\`\n${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\n\`\`\``);
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed] });
await addSettingsButton(messageReference);
}
} catch (error) {
console.log(error);
try {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
.setTitle('Error')
.setDescription(`Sorry, something went wrong and the output is not available.\n> **Text:**\n\`\`\`\n${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\n\`\`\``);
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed] });
await addSettingsButton(messageReference);
} catch (error) {}
}
}
async function handleSuccessfulSpeechGeneration(interaction, text, language, outputUrl) {
try {
const isGuild = interaction.guild !== null;
const file = new AttachmentBuilder(outputUrl).setName('speech.wav');
const embed = new EmbedBuilder()
.setColor(hexColour)
.setAuthor({ name: `To ${interaction.user.displayName}`, iconURL: interaction.user.displayAvatarURL() })
.setDescription(`Here Is Your Generated Speech\n**Prompt:**\n\`\`\`${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\`\`\``)
.addFields({ name: '**Generated by**', value: `\`${interaction.user.displayName}\``, inline: true }, { name: '**Language Used:**', value: `\`${language}\``, inline: true })
.setTimestamp();
if (isGuild) {
embed.setFooter({ text: interaction.guild.name, iconURL: interaction.guild.iconURL() || 'https://ai.google.dev/static/site-assets/images/share.png' });
}
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed], files: [file] });
await addSettingsButton(messageReference);
} catch (error) {
console.log(error.message);
}
}
async function handleSuccessfulMusicGeneration(interaction, text, outputUrl) {
try {
const isGuild = interaction.guild !== null;
const file = new AttachmentBuilder(outputUrl).setName('music.mp4');
const embed = new EmbedBuilder()
.setColor(hexColour)
.setAuthor({ name: `To ${interaction.user.displayName}`, iconURL: interaction.user.displayAvatarURL() })
.setDescription(`Here Is Your Generated Music\n**Prompt:**\n\`\`\`${text.length > 3900 ? text.substring(0, 3900) + '...' : text}\`\`\``)
.addFields({ name: '**Generated by**', value: `\`${interaction.user.displayName}\``, inline: true })
.setTimestamp();
if (isGuild) {
embed.setFooter({ text: interaction.guild.name, iconURL: interaction.guild.iconURL() || 'https://ai.google.dev/static/site-assets/images/share.png' });
}
const messageReference = await interaction.channel.send({ content: `${interaction.user}`, embeds: [embed], files: [file] });
await addSettingsButton(messageReference);
} catch (error) {
console.log(error.message);