-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.ts
349 lines (288 loc) · 8.74 KB
/
main.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
/// <reference lib="deno.unstable" />
import { existsSync, walk } from "https://deno.land/std@0.221.0/fs/mod.ts";
import importLLMFile from "./lib/importLLMFile.ts";
if (!existsSync("./bots")) {
throw new DOMException(
"Add the /bots directory and populate it with LLMFiles to use the bot! As an example, copy the directory from the Github.",
"NoLLMsAddedError",
);
}
for await (const entry of await walk("./bots")) {
if (entry.isFile && entry.name.endsWith(".ts")) {
await importLLMFile(
entry.path,
);
}
}
console.log("LLMs initialized.")
import * as types from "./main.d.ts";
type messageData = {
id: string;
messages: types.Message[];
};
import client from "./client.ts";
console.log(
"Everything looks good!",
Object.keys(availableLLMs).length,
"LLMs were imported.",
);
await import("./slashcode.ts");
import { ChannelType, Message } from "npm:discord.js";
const db = await Deno.openKv("./db.sqlite");
function splitStringIntoChunks(
inputString: string,
chunkSize: number = 1999,
): string[] {
const lines: string[] = inputString.split("\n");
const chunks: string[] = [];
let currentChunk: string = "";
for (const line of lines) {
if (currentChunk.length + line.length + 1 > chunkSize) {
chunks.push(currentChunk.trim());
currentChunk = line;
} else {
if (currentChunk) {
currentChunk += "\n";
}
currentChunk += line;
}
}
if (currentChunk) {
chunks.push(currentChunk.trim());
}
return chunks;
}
/*
New database example:
{
channels: [1],
users: {
0: {
current_bot: "chatgpt",
current_conversation: 0,
conversations: {
chatgpt: [
{
id: "completion-37",
messages: [{}] // Alan, insert message object every time you finish here. Wait, Alan, are you still on the team?
}
]
}
}
},
}
*/
const getImagesFromMessage = async (message: Message<boolean>) => {
const images: string[] = [];
// Process attachments
message.attachments.forEach((image) => {
images.push(image.url);
});
// Process URLs in message content
const regx = message.content.match(
/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i,
);
if (regx) {
// Use Promise.all to wait for all asynchronous operations to complete
const resultArray = await Promise.all(regx.map(async (link) => {
const isImage = (await fetch(link)).headers.get("Content-Type")
?.startsWith("image/");
if (isImage) {
console.log(link);
message.content.replace(link, "");
return link;
}
return null;
}));
const filteredImages: string[] = [];
resultArray.forEach((link) => {
if (link !== null) filteredImages.push(link);
});
images.push(...filteredImages);
}
// Process stickers
message.stickers.forEach((sticker) => {
images.push(sticker.url);
});
return images;
};
client.on("messageCreate", async (message) => {
let isBotChannel = (await db.get<boolean>([
"channels",
message.channel.id,
])).value;
if (isBotChannel === null) {
await db.set(
["channels", message.channel.id],
false,
);
isBotChannel = false;
}
if (message.author.bot || JSON.stringify(message.flags) === "4096") return; // The "4096" flag is the @silent flag on discord.
if (
message.channel.type === ChannelType.DM ||
isBotChannel
) {
let error = false; // Tracks if we've already pestered the user with an error / message :\
const llm =
(await db.get<string>(["users", message.author.id, "current_bot"])).value; // After reading the typedocs I realized this is the cleaner way to do this
if (llm === null) {
await message.reply(
"Looks like this is your first time using this bot! Run /info to learn how to use the full potential of this bot, and set your desired LLM using /set-ai!",
);
error = true;
return;
} else if (
!Object.prototype.hasOwnProperty.call(availableLLMs, llm)
) {
// current LLM is removed/corrupted
await message.reply(
"Your current LLM is corrupted or removed! Set a new LLM at /set-ai!",
);
return;
}
if (
availableLLMs[llm].information.highCostLLM &&
Deno.env.get("PREMIUM_ENFORCEMENT") === "true"
) {
const guild = client.guilds.resolve(Deno.env.get("PRIMARY_GUILD") || "0");
if (guild) {
const member = await guild?.members.fetch(message.author.id);
if (
!member.premiumSince &&
Deno.env.get("PRIMARY_GUILD") !== message.guild?.id
) {
message.reply(
"This LLM is for premium users only! Boost the server to gain access to this LLM, or join the bot host's primary server!",
);
return;
}
} else {
message.reply(
"your developer is terrible at his job (Premium lock config not set properly! This LLM is marked as high-cost, have the owner of the bot finish setup.)",
);
return;
}
}
let isMessageProcessing = (await db.get<boolean>([
"users",
message.author.id,
"messageWaiting",
])).value;
if (isMessageProcessing) {
try {
await message.delete();
return;
} catch (_err) {
await message.reply("A message is already being processed!");
return;
}
} else {
isMessageProcessing = true;
await db.set(
["users", message.author.id, "messageWaiting"],
isMessageProcessing,
);
}
let curconv = (await db.get<number>([
"users",
message.author.id,
"current_conversation",
])).value;
if (curconv === null) {
// They haven't used this LLM before
curconv = 0;
await db.set(
["users", message.author.id, "current_conversation"],
curconv,
);
if (error === false) {
await message.reply(
"Started conversation! Use /wipe to reset this conversation.",
);
error = true;
}
}
let messages = (await db.get<messageData[]>([
"users",
message.author.id,
"conversations",
llm,
])).value!;
if (messages === null) {
// No conversations for this LLM.
messages = [{
id: "New Conversation",
messages: [],
}];
if (error === false) {
await message.reply(
"Started conversation! Use /wipe to reset this conversation.",
);
}
}
const curmsgs = messages[curconv].messages;
const msg = await message.reply("Sending message...");
const requirements = availableLLMs[llm].information;
const reqobject: types.Requirements = {};
if (requirements.multiModal) {
const images: string[] = await getImagesFromMessage(message);
reqobject.images = images;
}
if (requirements.env) {
reqobject.env = {};
requirements.env.forEach((envValue) => {
if (!Deno.env.get(envValue)) {
throw `Required env value "${envValue}" not found, add it to .env!`;
}
reqobject.env![envValue] = Deno.env.get(envValue)!;
});
}
reqobject.streaming = false; // No.
try {
const resp = await availableLLMs[llm].send(
message.content,
curmsgs,
null,
reqobject,
);
messages[curconv].messages = resp.messages;
await db.set(
["users", message.author.id, "conversations", llm],
messages,
);
const messagechunks = splitStringIntoChunks(
resp.choices[0].message.content!,
2000,
);
let cvalue = 0;
messagechunks.forEach((chunk) => {
if (cvalue === 0) {
cvalue = 1;
isMessageProcessing = false;
db.set(
["users", message.author.id, "messageWaiting"],
isMessageProcessing,
);
msg.edit(chunk);
} else {
message.reply(chunk);
}
});
} catch (err) {
isMessageProcessing = false;
db.set(
["users", message.author.id, "messageWaiting"],
isMessageProcessing,
);
msg.edit(
"LLM threw an error in processing! Contact the admins to have them handle and report the bug.",
);
console.error(
`Model ${llm} threw an error! If you can't understand the error, contact the developer (Eris) for help. Error:`,
err,
);
return;
}
}
});