-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.js
1556 lines (1383 loc) · 55.7 KB
/
bot.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 fs from "node:fs";
import path from "node:path";
import {
Client,
Collection,
Events,
GatewayIntentBits,
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
TextChannel,
NewsChannel,
ButtonComponent,
ThreadChannel,
Partials,
ChannelType,
EmbedBuilder,
PermissionFlagsBits,
} from "discord.js";
import { main } from "./commands/dalle/aart.js";
import { invocationWorkflow, preWorkflow } from "./invocation.js";
import { invocationWorkflowSB, preWorkflowSB } from "./supabase-invocations.js";
import { quosLogic } from "./commands/quoordinates/quos.js";
import { lookupBook } from "./books.js";
import { complete } from "./openai_helper.js";
import { generateClozeDeletion } from "./anki.js";
import { CronJob } from "cron";
import { randomExport } from "./commands/quoordinates/random.js";
import { quoteRoyale } from "./quote-royale.js";
import { processQueue, queue } from "./shared-queue.js";
import { createModal } from "./modal.js";
import { createClient } from "@supabase/supabase-js";
import { tts } from "./tts.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildMembers,
],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
});
// import config from "./config.json" assert { "type": "json" };
import dotenv from "dotenv";
dotenv.config();
const { supabaseUrl, supabaseKey } = process.env;
const supabase = createClient(supabaseUrl, supabaseKey, {
auth: {
persistSession: false,
},
});
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
const channelId = "1151221056951038025"; // replace with your channel ID
const job = new CronJob(
"*/60 * * * *",
async () => {
try {
console.log("You will see this message every hour");
const randomArr = await randomExport(1);
let random = randomArr[0];
while (random.text.length > 2000) {
randomArr = await randomExport(1);
random = randomArr[0];
}
const channel = await client.channels.fetch(channelId);
// const repost = new ButtonBuilder()
// .setCustomId("repost")
// .setLabel("new-home")
// .setStyle(ButtonStyle.Primary);
// const makeAart = new ButtonBuilder()
// .setCustomId("aart_btn")
// .setLabel("draw")
// .setStyle(ButtonStyle.Primary);
// const learnMore = new ButtonBuilder()
// .setCustomId("quos_learn_more")
// .setLabel("delve")
// .setStyle(ButtonStyle.Primary);
const summarize = new ButtonBuilder()
.setCustomId("summarize")
.setLabel("tldr")
.setStyle(ButtonStyle.Primary);
const share = new ButtonBuilder()
.setCustomId("share")
.setLabel("share")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(summarize, share);
await channel.send({
content: `> ${random.text}\n\n-- [${
random.book.title
} (**affiliate link**)](${await lookupBook(random.book.title)})`,
components: [row],
});
} catch (err) {
console.error(err);
}
},
null,
true,
"America/New_York"
);
job.start();
// create a job to run quoteRoyale(client); every day at 12:00 AM EST
const job2 = new CronJob(
"0 0 * * *",
async () => {
try {
console.log("You will see this message every day at 12:00 AM EST");
await quoteRoyale(client);
} catch (err) {
console.error(err);
}
},
null,
true,
"America/New_York"
);
job2.start();
});
client.commands = new Collection();
const foldersPath = new URL("./commands", import.meta.url).pathname;
const commandFolders = fs.readdirSync(foldersPath);
for (const folder of commandFolders) {
const commandsPath = path.join(foldersPath, folder);
const commandFiles = fs
.readdirSync(commandsPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(commandsPath, file);
const command = await import(filePath);
// Set a new item in the Collection with the key as the command name and the value as the exported module
if ("data" in command && "execute" in command) {
client.commands.set(command.data.name, command);
} else {
console.log(
`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`
);
}
}
}
client.on(Events.MessageReactionAdd, async (reaction, user) => {
// When a reaction is received, check if the structure is partial
if (reaction.partial) {
// If the message this reaction belongs to was removed, the fetching might result in an API error which should be handled
try {
await reaction.fetch();
} catch (error) {
console.error("Something went wrong when fetching the message:", error);
// Return as `reaction.message.author` may be undefined/null
return;
}
}
// Now the message has been cached and is fully available
console.log(
`${reaction.message.author}'s message "${reaction.message.content}" gained a reaction!`
);
// The reaction is now also fully available and the properties will be reflected accurately:
console.log(
`${reaction.count} user(s) have given the same reaction to this message! ${reaction.emoji.name}`
);
// log the reaction and if reaction is :floppy_disk: then dm the user with the message content and the url to the message
if (reaction.emoji.name === "💾") {
await user.send(`${reaction.message.content}\n\n${reaction.message.url}`);
}
});
client.on(Events.InteractionCreate, async (interaction) => {
if (!interaction.isChatInputCommand() && !interaction.isButton()) return;
// List of channel IDs where the bot should respond
// const allowedChannels = ['1144620340509675541'];
// if (!allowedChannels.includes(interaction.channelId) && process.env.NODE_ENV !== 'production') {
// return interaction.reply({ content: 'I\'m not allowed to interact in this channel!', ephemeral: true });
// }
if (interaction.isButton()) {
if (interaction.customId === "summarize") {
interaction.commandName = "summarize";
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
queue.push({
task: async (user, message) => {
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
const summary = await complete(
`tldr to one or two sentences this:\n${interaction.message.content
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.trim()}`
);
const res = await interaction.followUp(summary);
interaction.commandName = "summarize";
await invocationWorkflowSB(interaction, true);
await message.edit({
content: `<@${user}>, your \`/tldr\` request has been processed! Link: ${res.url}`,
ephemeral: true,
});
},
user: interaction.user.id,
interaction: interaction,
message: sentMessage,
});
processQueue();
} else if (interaction.customId === "quiz") {
interaction.commandName = "quiz";
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
queue.push({
task: async (user, message) => {
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
const quiz = await complete(
`Hey Teachers assistant! Turn this quote into a one to three question quiz (your discretion). The form should be "Question: ||Answer||". Make sure to surround answer with "||" so its hidden from the students. Just return the quiz and nothing else.\n\nQuote:\n${interaction.message.content
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.trim()}`
);
const res = await interaction.followUp(quiz);
interaction.commandName = "quiz";
await invocationWorkflowSB(interaction, true);
await message.edit({
content: `<@${user}>, your \`/quiz\` request has been processed! Link: ${res.url}`,
ephemeral: true,
});
},
user: interaction.user.id,
interaction: interaction,
message: sentMessage,
});
processQueue();
} else if (interaction.customId === "pseudocode") {
interaction.commandName = "pseudocode";
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
queue.push({
task: async (user, message) => {
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
/*
await complete(
`You are a surrealist creative technologist who has a graduate degree in Computer Science and mathematics. You are paid very well to think outside the box and come up with never before thought of surreal app ideas, your ideas are always hits on the app store because there are no similar offerings. You don't come up with boring ideas that are straightforward, you deeply think about your quote and provide your clients the best option. You have access to the GPT-4 API, ReactJS, Go Lang for CLI apps, Swift for iOS apps, p5.js and three.js for web canvas, and any HTTP calls. You usually recommend short scripts that are runnable standalone. If you'd like to use any libraries or SaaS tools, merely add a comment as to what they are and why. Use this quote and convert it to an app idea and psuedocode. Total should be less than 1000 chars. If you use \`\`\` for the pseudocode make sure to include the programming language e.g. \`\`\`swift or \`\`\`js or \`\`\`go for example. Choose whatever language is best.\n\nQuote:\n${interaction.message.content
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.trim()}`
);
*/
const pseudocodeRes = await complete(
`I only have the following quote, recreate outside context using concepts from the world. Do a breadth first search of external data. This means that you are **not rephrasing the content in the quote**. You are pulling in examples and information from the world **outside the set** of the quote. Do not bother repeating or rehashing the quote.\n\nQuote:\n${interaction.message.content
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.trim()}`
);
// // split the pseudocodeRes into the description and code block (specified by ```)
// const pseudocodeResSplit = pseudocodeRes.split("```");
// const pseudocodeResDescription = pseudocodeResSplit[0];
// const pseudocodeResCodeBlock = pseudocodeResSplit[1];
// // fence the code block with ``` and the language if not already
// const pseudocodeResCodeBlockFenced =
// pseudocodeResCodeBlock.startsWith("```") &&
// pseudocodeResCodeBlock.endsWith("```")
// ? pseudocodeResCodeBlock
// : `\`\`\`${pseudocodeResCodeBlock.trim()}\`\`\``;
// // if either is greater than 2000 chars, return gracefully
// if (
// pseudocodeResDescription.length > 2000 ||
// pseudocodeResCodeBlockFenced.length > 2000
// ) {
// await interaction.editReply({
// content: `<@${user}>, your \`/pseudocode\` request has been processed! However, the result was too long to post in a single message. Please try again.`,
// ephemeral: true,
// });
// return;
// }
// const res = await interaction.followUp(pseudocodeResDescription);
// await interaction.followUp(pseudocodeResCodeBlockFenced);
const split2000 = [];
let i = 0;
while (i < pseudocodeRes.length) {
split2000.push(pseudocodeRes.substring(i, i + 2000));
i += 2000;
}
const res = await interaction.followUp(split2000[0]);
for (const part of split2000) {
// skip the first part
if (part === split2000[0]) {
continue;
}
await interaction.followUp(part);
}
// await interaction.followUp(pseudocodeRes);
interaction.commandName = "pseudocode";
await invocationWorkflowSB(interaction, true);
await message.edit({
content: `<@${user}>, your \`/pseudocode\` request has been processed! Link: ${res.url}`,
ephemeral: true,
});
},
user: interaction.user.id,
interaction: interaction,
message: sentMessage,
});
processQueue();
} else if (interaction.customId === "speak") {
// send message to channel files: [attachment]
try {
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
queue.push({
task: async (user, message) => {
interaction.commandName = "speech";
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
// get content of message rplace the affiliate link with nothing
const messageContent = interaction.message.content
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.replace(/--/, "From: ")
.trim();
const ttsUrl = await tts(messageContent);
const res = await interaction.followUp({
content: ``,
files: [ttsUrl],
});
interaction.commandName = "speech";
await invocationWorkflowSB(interaction, false, messageContent);
await interaction.editReply({
content: `<@${interaction.user.id}>, your \`/speech\` request has been processed. Link to result: ${res.url}`,
ephemeral: true,
});
},
user: interaction.user,
message: sentMessage,
interaction: interaction,
});
processQueue();
} catch (err) {
await interaction.reply({
content: `Something went wrong: ${err}`,
});
}
} else if (interaction.customId.includes("add-thoughts-btn")) {
const id = interaction.customId.split("_")[1];
let messageContent = interaction.message.content
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.trim();
// remove leading > if it exists
if (messageContent.startsWith(">")) {
messageContent = messageContent.slice(1);
}
if (messageContent.includes("--")) {
messageContent = messageContent.split("--")[0].trim();
}
const modal = await createModal(
"Add Thought",
"add-thought_" + id,
"",
"What are your thoughts on this quote?",
"My thoughts are...",
"thoughtInput"
);
await interaction.showModal(modal);
} else if (interaction.customId.includes("post-thought_")) {
// log msg
console.log(interaction.message.content);
await interaction.reply({
content: "Your thought has been added!",
ephemeral: true,
});
} else if (interaction.customId === "follow_up_questions") {
await interaction.deferReply({
ephemeral: true,
});
// use complete to generate three follow up questions based on the interaction.message.content
// user then sees three questions
// they can click buttons 1, 2, 3 for a quos on that question
// todo make it work for all three questions not just the first one
// todo respond in thread to follow up follow ups
// todo why do some interactions fail randomly? collector? length of text?
const followUpQuestions = await complete(
`What are three follow up questions to this quote? These questions should all be unique, simple conceptually and very different from one another. One question for each of the following (if applicable): people places and things.\n\n${interaction.message.content
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.replace(/\(\*\*affiliate link\*\*\)/g, "")}`,
"gpt-3.5-turbo"
);
const followUpQuestionsArray = followUpQuestions.split("\n");
const followUpQuestionsArrayTrimmed = followUpQuestionsArray.map((q) =>
q.trim()
);
const followUpQuestionsArrayFiltered =
followUpQuestionsArrayTrimmed.filter((q) => q !== "");
const followUpQuestionsArrayFilteredUnique = [
...new Set(followUpQuestionsArrayFiltered),
];
const followUpQuestionsArrayFilteredUniqueThree =
followUpQuestionsArrayFilteredUnique.slice(0, 3);
console.log(followUpQuestionsArrayFilteredUniqueThree);
const followUpQuestionsArrayFilteredUniqueThreeString =
followUpQuestionsArrayFilteredUniqueThree.join("\n");
const btn_question_one = new ButtonBuilder()
.setCustomId("btn_question_one")
.setLabel("1")
.setStyle(ButtonStyle.Primary);
const btn_question_two = new ButtonBuilder()
.setCustomId("btn_question_two")
.setLabel("2")
.setStyle(ButtonStyle.Primary);
const btn_question_three = new ButtonBuilder()
.setCustomId("btn_question_three")
.setLabel("3")
.setStyle(ButtonStyle.Primary);
const row = new ActionRowBuilder().addComponents(
btn_question_one,
btn_question_two,
btn_question_three
);
await interaction.followUp({
content: followUpQuestionsArrayFilteredUniqueThreeString,
components: [row],
ephemeral: true,
});
const collectorFilter = (i) => {
return i.user.id === interaction.user.id;
};
const collector = interaction.channel.createMessageComponentCollector({
filter: collectorFilter,
time: 60000,
});
collector.on("collect", async (i) => {
if (i.customId === "btn_question_one") {
console.log(i);
await i.deferReply();
const quos = await quosLogic(
followUpQuestionsArrayFilteredUniqueThree[0]
);
const quotes = quos
.filter((q) => q.text.length < 2000)
.filter((q) => {
console.log("debug");
console.log(q.text);
console.log(interaction.message.content);
return !interaction.message.content.includes(q.text);
})
.map(
async (q) =>
`> ${q.text}\n\n-- ${
(await lookupBook(q.title))
? `[${q.title} (**affiliate link**)](${await lookupBook(
q.title
)})`
: q.title
}\n\n`
);
const thread = await i.channel.threads.create({
name:
followUpQuestionsArrayFilteredUniqueThree[0]
.replace(/^\d+\.\s/, "")
.slice(0, 50) + "...",
autoArchiveDuration: 60,
startMessage: i.channel.lastMessage,
type: ChannelType.GUILD_PUBLIC_THREAD,
reason: "Sending quotes as separate messages in one thread",
});
for (const quote of quotes) {
await thread.send({
content: quote,
components: [],
});
}
await i.editReply(`Results: ${quotes.length} quotes`);
}
if (i.customId === "btn_question_two") {
await i.deferReply();
const quos = await quosLogic(
followUpQuestionsArrayFilteredUniqueThree[1]
);
await i.followUp(quos);
}
if (i.customId === "btn_question_three") {
await i.deferReply();
const quos = await quosLogic(
followUpQuestionsArrayFilteredUniqueThree[2]
);
await i.followUp(quos);
}
});
} else if (interaction.customId.includes("qroyale__quote_")) {
// on button click show ephemeral message thanking user for voting
// if user has already voted, show ephemeral message saying they can only vote once per day
// await interaction.deferReply();
const buttonId = interaction.customId;
const quoteNumber = Number(buttonId.split("qroyale__quote_")[1]);
// const quotesVotes = JSON.parse(fs.readFileSync("./quotes-votes.json"));
// last row in db
const { data, error } = await supabase
.from("quote-votes")
.select("*")
.order("id", { ascending: false })
.limit(1);
if (error) {
console.log(error);
return;
}
const quotesVotes = data[0];
const userId = interaction.user.id;
// { quotes: quotes, votes: [0,0,0,0,0], voters: [] }
const voters = quotesVotes.voters;
if (voters.includes(userId)) {
await interaction.reply({
content: `You have already voted today! Check back tomorrow (EST) for the results. And come back tomorrow to vote again on a new set of quotes!`,
ephemeral: true,
});
return;
}
quotesVotes.votes[quoteNumber - 1] =
quotesVotes.votes[quoteNumber - 1] + 1;
quotesVotes.voters.push(userId);
// fs.writeFileSync(
// "./quotes-votes.json",
// JSON.stringify(quotesVotes, null, 2)
// );
// update db
const { data: data2, error: error2 } = await supabase
.from("quote-votes")
.update({ votes: quotesVotes.votes, voters: quotesVotes.voters })
.eq("id", quotesVotes.id);
if (error2) {
console.log(error2);
return;
}
await interaction.reply({
content: `You voted for quote ${quoteNumber}! Check back tomorrow (EST) for the results. And come back tomorrow to vote again on a new set of quotes!`,
ephemeral: true,
});
} else if (interaction.customId === "aart_btn") {
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
queue.push({
task: async (user, message) => {
interaction.commandName = "draw";
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
const { prompt, imageUrl } = await main(interaction.message.content);
if (prompt === "Error generating prompt.") {
await interaction.editReply({
content: "Something went wrong. Please try again.",
ephemeral: true,
});
return;
}
// save image to cf from imageUrl
const cfRes = await fetch(process.env.quoordinates_server_dalle_cf, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ url: imageUrl }),
});
const cfResJson = await cfRes.json();
const cfResUrl = cfResJson.result;
// send message to channel
const channelMsg = await interaction.channel.send(
`Art Prompt (**save the image it disappears in 24 hours!**): ${prompt} \n Image: [(url)](${cfResUrl})`
);
interaction.commandName = "draw";
await invocationWorkflowSB(interaction, true);
await interaction.editReply({
content: `<@${interaction.user.id}>, your request has been completed. Link to result: ${channelMsg.url}`,
ephemeral: true,
});
},
user: interaction.user,
message: sentMessage,
interaction,
});
processQueue();
} else if (interaction.customId === "share") {
/*
1. get an image url from aart
2. post to quoordinates server with the following
{
"text": {userInput},
"url": {imageUrl}
}
3. get back a url and reply with it
*/
// await interaction.deferReply();
const sentMessage = await interaction.reply({
content: `<@${interaction.user.id}>, your request has been added to the queue.`,
ephemeral: true,
});
try {
queue.push({
task: async (user, message) => {
interaction.commandName = "share";
if (!(await preWorkflowSB(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
let userInput = interaction.message.content.trim();
// remove [cover](url) from userInput
const regex = /\[cover\]\((.*)\)/;
const match = userInput.match(regex);
if (match) {
userInput = userInput.replace(match[0], "").trim();
}
// remove leading >
userInput = userInput.replace(/^>/, "").trim();
// remove any markdown links
userInput = userInput.replace(/\[(.*?)\]\((.*?)\)/g, "$1");
// remove (**affiliate link**) from userInput
userInput = userInput
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.trim();
// await interaction.followUp("This feature is not yet implemented.");
const { prompt, imageUrl } = await main(userInput);
if (prompt === "Error generating prompt.") {
await interaction.followUp({
content: "Something went wrong. Please try again.",
ephemeral: true,
});
return;
}
const response = await fetch(
process.env.quoordinates_server_share,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ text: userInput, url: imageUrl }),
}
);
const json = await response.json();
console.log(json);
if (json.error) {
await interaction.followUp({
content: "Something went wrong. Please try again.",
ephemeral: true,
});
return;
}
const shareUrlHorizontal = json.result.horizontal;
const shareUrlVertical = json.result.vertical;
const res = await interaction.followUp(
`Art Prompt: ${prompt}\n\nHorizontal:\n\n${shareUrlHorizontal}\n\nVertical:\n\n${shareUrlVertical}`
);
interaction.commandName = "share";
await invocationWorkflowSB(interaction, true);
await message.edit({
content: `<@${user}>, your \`/share\` request has been processed! Link: ${res.url}`,
ephemeral: true,
});
},
user: interaction.user.id,
interaction: interaction,
message: sentMessage,
});
processQueue();
} catch (err) {
console.log(err);
await interaction.followUp({
content: "Something went wrong. Please try again.",
ephemeral: true,
});
}
} else if (interaction.customId === "cloze_deletion") {
interaction.commandName = "cloze_deletion";
await preWorkflow(interaction);
await interaction.deferReply({
ephemeral: true,
});
const text = interaction.message.content
.replace(/\[(.*?)\]\((.*?)\)/g, "$1")
.replace(/\(\*\*affiliate link\*\*\)/g, "")
.replace(/^>/, "")
.trim();
const cloze = await generateClozeDeletion(text);
await interaction.editReply({
content: "done! see quiz below",
ephemeral: true,
});
await interaction.channel.send({
content: `${cloze}\n\nLink to original message: https://discord.com/channels/${interaction.guildId}/${interaction.channelId}/${interaction.message.id}`,
ephemeral: false,
});
interaction.commandName = "cloze_deletion";
await invocationWorkflowSB(interaction, true);
} else if (interaction.customId === "repost") {
interaction.commandName = "repost";
if (!(await preWorkflow(interaction))) {
await interaction.editReply({
content:
"You have reached your monthly limit for this command: " +
interaction.commandName +
". You can get more invocations by supporting the project [here](https://www.bramadams.dev/discord/)!",
ephemeral: true,
});
return;
}
await interaction.deferReply({
ephemeral: true,
});
const channels = [
{
name: "00-cs-info",
description:
"This section covers general works that include a variety of topics, often serving as reference materials. Encyclopedias, bibliographies, journals, and other compilations fall under this classification. It also includes works on computers, information technology, and data processing, which are increasingly significant in this digital age. Items related to journalism and news media can also be found here.",
id: "1148700226996154518",
tags: [
"generalities",
"encyclopedia",
"encyclopedias",
"computer",
"computers",
"information technology",
"journalism",
"news media",
],
},
{
name: "100-phil-psy",
description:
"This category focuses on human thought, reasoning, and the mind. Works in philosophy discuss fundamental issues like existence, morality, and knowledge, while psychology texts explore mental processes, behavior, and the human psyche. Classical philosophical treatises and contemporary psychological studies both find their home in this section.",
id: "1148693095655940187",
tags: [
"philosophy",
"psychology",
"psychoanalysis",
"psychotherapy",
"psychotherapist",
"psychoanalyst",
"psychologist",
"psychiatrist",
"psychiatry",
],
},
{
name: "200-religion",
description:
"This section contains works related to religious beliefs, practices, and institutions. Texts from a wide array of religious traditions including Christianity, Islam, Hinduism, Buddhism, and others are categorized here. Topics may range from sacred texts and theology to religious history and comparative religion.",
id: "1148693201012662292",
tags: ["religion", "faith", "spirituality", "theology"],
},
{
name: "300-soc-sci",
description:
"This category encompasses works that study human society and social relationships. Subjects such as economics, politics, law, education, and sociology fall under this section. It offers a broad overview of how human groups function, interact, and are governed.",
id: "1148693249737887815",
tags: [
"social science",
"social sciences",
"economics",
"politics",
"law",
"education",
"sociology",
],
},
{
name: "400-lang",
description:
"This section is dedicated to works that explore the complexities of language and linguistics. It includes dictionaries, grammars, and instructional material for learning different languages. Topics may range from the structure of language to the study of specific languages and language families.",
id: "1148693285330763907",
tags: [
"language",
"languages",
"linguistics",
"grammar",
"dictionary",
"dictionaries",
],
},
{
name: "500-science",
description:
"This section houses texts related to the natural world and its phenomena, from physics and chemistry to earth sciences and biology. Mathematics books also find their place here, covering topics from arithmetic to advanced calculus and theoretical mathematics.",
id: "1148693329203167334",
tags: [
"science",
"physics",
"chemistry",
"biology",
"earth science",
"math",
"mathematics",
],
},
{
name: "600-tech",
description:
"This category covers practical sciences and their applications in daily life. Subfields include medicine, engineering, agriculture, home economics, and many other technologies that shape modern society. Manuals, guides, and professional literature are typical in this section.",
id: "1148693368742883399",
tags: [
"technology",
"applied science",
"applied sciences",
"medicine",
"engineering",
"agriculture",
"home economics",
],
},
{
name: "700-arts",
description:
"This section is a hub for works related to the arts, entertainment, and recreation. Whether it's painting, music, theater, sports, or photography, this classification provides a home for the creative and recreational aspects of human culture.",
id: "1148693419854659615",
tags: ["art", "arts", "recreation", "music", "sports", "games"],
},
{
name: "800-lit",
description:
"This section is devoted to literature in all its forms, including poetry, essays, drama, and fiction. Works are often organized by their original language or country of origin, providing a global perspective on literary traditions. Anthologies, literary criticism, and works on writing techniques are also found here.",
id: "1148693465073467472",
tags: [
"literature",
"poetry",
"essay",
"essays",
"drama",
"fiction",
"novel",
"novels",
"book",
"books",
"shakespeare",
],
},
{
name: "900-hist-geo",
description:
"This section contains works that explore the human past and the world around us. Histories of various nations, civilizations, and significant events are grouped here, along with geographical works that examine the Earth's features and political boundaries. Travel guides, atlases, and maps are common in this category.",
id: "1148693527228850227",
tags: [
"history",
"geography",
"historical",
"historian",