-
Notifications
You must be signed in to change notification settings - Fork 3
/
helpers-utility.js
501 lines (461 loc) ยท 12.6 KB
/
helpers-utility.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
const { encode } = require("@nem035/gpt-3-encoder");
const logger = require("./src/logger.js")("helpers-utility");
const { supabase } = require("./src/supabaseclient");
const testString = "calculator:add(12,24)";
// const capabilityRegex = /(\w+):(\w+)\(([^)]*?)\)/g;
const capabilityRegexGlobal = /(\w+):(\w+)\((.*?)\)/g;
const capabilityRegexSingle = /(\w+):(\w+)\((.*?)\)/;
// test out the global and single
const matchGlobal = testString.match(capabilityRegexGlobal) || [];
const matchSingle = testString.match(capabilityRegexSingle) || [];
logger.info(`Regex test on ${testString}: ${matchGlobal.join(" ")}`);
logger.info(`Regex test on ${testString}: ${matchSingle.join(" ")}`);
/**
* Counts the number of tokens in a string.
* @param {string} text - The string to count the tokens in.
* @returns {number} - The number of tokens in the string.
*/
function countTokens(text) {
const encodedText = encode(text.toString());
return encodedText.length;
}
/**
* Counts the number of tokens in an array of messages.
* @param {Array} messages - The array of messages to count the tokens in.
* @returns {number} - The number of tokens in the array of messages.
*/
function countTokensInMessageArray(messages = []) {
if (!messages || messages.length === 0) {
return 0;
}
return messages.reduce((totalTokens, message) => {
const messageText = JSON.stringify(message);
const messageTokens = countTokens(messageText);
return totalTokens + messageTokens;
}, 0);
}
/**
* Removes a mention from a message.
* @param {string} message - The message to remove the mention from.
* @param {string} mention - The mention to remove.
* @returns {string} - The message with the mention removed.
*/
function removeMentionFromMessage(message, mention) {
const mentionRegex = new RegExp(`<@${mention}>`, "g");
return message.replace(mentionRegex, "").trim();
}
/**
* Displays a typing indicator for the given message.
* @param {string} message - The message to display the typing indicator for.
* @returns {number} - The interval ID for the typing indicator.
*/
function displayTypingIndicator(message) {
startTypingIndicator(message);
const typingInterval = setTypingInterval(message);
return typingInterval; // To allow for clearing the interval outside of this function
}
/**
* Starts the typing indicator in the specified message's channel.
* @param {Message} message - The message object.
*/
function startTypingIndicator(message) {
try {
message.channel.sendTyping();
logger.info("Started typing indicator");
} catch (error) {
logger.error(`Error starting typing indicator: ${error}`);
}
}
/**
* Sets an interval to send typing indicator in a channel.
* @param {Message} message - The message object.
* @returns {number} - The ID of the interval.
*/
function setTypingInterval(message) {
return setInterval(() => {
try {
message.channel.sendTyping();
logger.info("Typing indicator sent");
} catch (error) {
logger.error(`Error sending typing indicator: ${error}`);
}
}, 5000);
}
/**
* Splits a message into chunks and sends them as separate messages.
* @param {string} messageText - The message text to be split and sent.
* @param {object} channel - The channel to send the message to.
* @returns {void}
*/
function splitAndSendMessage(messageText, channel) {
if (!channel) {
logger.info("splitAndSendMessage: channel is null or undefined");
return;
}
if (typeof messageText !== "string") {
logger.info("splitAndSendMessage: messageText is not a string");
return;
}
// make sure channel exists
if (!channel) {
logger.error("splitAndSendMessage: channel does not exist");
return;
}
logger.info(`splitAndSendMessage: message length: ${messageText.length}`);
// make sure the channel is a Discord channel
if (!channel.send) {
logger.error("splitAndSendMessage: channel does not have a send method");
return;
}
if (messageText.length < 2000) {
try {
channel.send(messageText);
} catch (error) {
logger.error(`Error sending message: ${error}`);
}
} else {
const messageChunks = splitMessageIntoChunks(messageText);
messageChunks.forEach((chunk, index) => {
try {
channel.send(chunk);
} catch (error) {
logger.error(`Error sending message chunk ${index}: ${error}`);
}
});
}
}
/**
* Splits a message string into chunks.
* @param {string} messageText - The message text to be split.
* @returns {Array<string>} - An array containing the chunks of the message.
*/
function splitMessageIntoChunks(messageText) {
if (typeof messageText !== "string") {
logger.info("splitMessageIntoChunks: messageText is not a string");
return [];
}
const words = messageText.split(" ");
const messageChunks = [];
let currentChunk = "";
words.forEach((word) => {
if (currentChunk.length + word.length + 1 <= 2000) {
currentChunk += `${word} `;
} else {
messageChunks.push(currentChunk.trim());
currentChunk = `${word} `;
}
});
if (currentChunk.length > 0) {
messageChunks.push(currentChunk.trim());
}
return messageChunks;
}
/**
* Parses a JSON string into a JavaScript object.
* @param {string} jsonString - The JSON string to be parsed.
* @returns {Object} - The JavaScript object parsed from the input JSON string.
* @throws {SyntaxError} If the input string is not a valid JSON.
*/
function parseJSONArg(jsonString) {
return JSON.parse(jsonString.replace(/'/g, '"'));
}
/**
* Cleans a URL for use with Puppeteer by removing leading and trailing quotes.
* @param {string} url - The URL to clean.
* @returns {string} - The cleaned URL.
*/
function cleanUrlForPuppeteer(url) {
return url.replace(/^['"]|['"]$/g, "");
}
/**
* Delays execution for a specified number of milliseconds.
* @param {number} ms - The number of milliseconds to delay.
* @returns {Promise} - A promise that resolves after the specified delay.
*/
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Processes chunks of data asynchronously with a provided processing function.
* @param {Array} chunks - The data chunks to process.
* @param {Function} processFunction - The function to process each chunk. Must return a Promise.
* @param {number} [concurrencyLimit=2] - The number of chunks to process concurrently.
* @param {Object} [options={}] - Additional options for the processing function.
* @returns {Promise<Array>} - A promise that resolves to an array of processed chunk results.
*/
async function processChunks(
chunks,
processFunction,
concurrencyLimit = 2,
options = {}
) {
const results = [];
const filteredChunks = chunks.filter((chunk) => chunk.length > 0);
for (let i = 0; i < filteredChunks.length; i += concurrencyLimit) {
const chunkBatch = filteredChunks.slice(i, i + concurrencyLimit);
const batchResults = await Promise.all(
chunkBatch.map(async (chunk, index) => {
await sleep(500);
return processFunction(chunk, options);
})
);
results.push(...batchResults);
}
return results;
}
/**
* Retrieves configuration data from Supabase.
* @returns {Promise<Object>} An object containing the configuration keys and values.
*/
async function getConfigFromSupabase() {
const { data, error } = await supabase.from("config").select("*");
// turn the array of objects into a big object that can be destructured
const configArray = data;
// get all the keys and values
const configKeys = configArray.map((config) => config.config_key);
const configValues = configArray.map((config) => config.config_value);
// return an object with all the keys and values
const config = Object.fromEntries(
configKeys.map((_, i) => [configKeys[i], configValues[i]])
);
return config;
}
// Example array of animal emojis
const emojis = [
"๐ถ",
"๐ฑ",
"๐ญ",
"๐น",
"๐ฐ",
"๐ฆ",
"๐ป",
"๐ผ",
"๐ปโโ๏ธ",
"๐จ",
"๐ฏ",
"๐ฆ",
"๐ฎ",
"๐ท",
"๐ธ",
"๐ต",
"๐",
"๐",
"๐",
"๐",
"๐",
"๐ง",
"๐ฆ",
"๐ค",
"๐ฃ",
"๐ฅ",
"๐ฆ",
"๐ฆ
",
"๐ฆ",
"๐ฆ",
"๐บ",
"๐",
"๐ด",
"๐ฆ",
"๐",
"๐ชฑ",
"๐",
"๐ฆ",
"๐",
"๐",
"๐",
"๐ฆ",
"๐ฆ",
"๐ท",
"๐ธ",
"๐ฆ",
"๐ข",
"๐",
"๐ฆ",
"๐ฆ",
"๐ฆ",
"๐",
"๐ฆ",
"๐ฆ",
"๐ฆ",
"๐ฆ",
"๐ก",
"๐ ",
"๐",
"๐ฌ",
"๐ณ",
"๐",
"๐ฆ",
"๐",
"๐
",
"๐",
"๐ฆ",
"๐ฆ",
"๐ฆง",
"๐",
"๐ฆ",
"๐ฆ",
"๐ช",
"๐ซ",
"๐ฆ",
"๐ฆ",
"๐ฆฌ",
"๐",
"๐",
"๐",
"๐",
"๐",
"๐",
"๐",
"๐ฆ",
"๐",
"๐ฆ",
"๐",
"๐ฉ",
"๐ฆฎ",
"๐โ๐ฆบ",
"๐",
"๐โโฌ",
"๐ชถ",
"๐",
"๐ฆ",
"๐ฆค",
"๐ฆ",
"๐ฆ",
"๐ฆข",
"๐ฆฉ",
"๐",
"๐",
"๐ฆ",
"๐ฆจ",
"๐ฆก",
"๐ฆซ",
"๐ฆฆ",
"๐ฆฅ",
"๐",
"๐",
"๐ฟ",
"๐ฆ",
];
// Set to store used emojis
const usedEmojis = new Set();
// Function to get a unique emoji
function getUniqueEmoji() {
let emoji;
do {
emoji = emojis[Math.floor(Math.random() * emojis.length)];
} while (usedEmojis.has(emoji));
usedEmojis.add(emoji);
if (usedEmojis.size === emojis.length) {
usedEmojis.clear();
}
return emoji;
}
/**
* Checks if a message contains a capability.
* @param {string} message - The message to check.
* @returns {boolean} - True if the message contains a capability, false otherwise.
*/
function doesMessageContainCapability(rawMessage) {
if (!rawMessage) {
logger.error(`Cannot check if message contains capability: ${rawMessage}`);
return false;
}
logger.info(`Checking if message contains capability: ${rawMessage}`);
// message might be a string, or an object with .content
// lets handle both
let content = "";
if (typeof rawMessage === "string") {
logger.info("Message is a string");
content = rawMessage;
} else if (typeof rawMessage === "object" && rawMessage.content) {
logger.info("Message is an object with content");
content = rawMessage.content;
} else {
logger.warn(
`Message is not a string or object with content: ${JSON.stringify(
rawMessage
)}`
);
return false;
}
// use regex to check if the message contains the capability
const regexMatches = content.match(capabilityRegexSingle);
// if there are no matches, return false
if (!regexMatches) {
return false;
}
logger.info(`Regex matches: ${regexMatches}`);
// otherwise, return true
return true;
}
/**
* Counts the number of tokens in an array of messages.
* @param {Array} messageArray - The array of messages to count tokens from.
* @returns {number} - The total number of tokens.
*/
function countMessageTokens(messageArray = []) {
let totalTokens = 0;
// logger.info("Message Array: ", messageArray);
if (!messageArray) {
return totalTokens;
}
if (messageArray.length === 0) {
return totalTokens;
}
// for loop
for (let i = 0; i < messageArray.length; i++) {
const message = messageArray[i];
// encode message.content
const encodedMessage = encode(JSON.stringify(message));
totalTokens += encodedMessage.length;
}
return totalTokens;
}
/**
* Destructures a string of arguments into an array of trimmed arguments.
* @param {string} argsString - The string of arguments to destructure.
* @returns {Array<string>} - An array of trimmed arguments.
*/
function destructureArgs(args) {
logger.info(`Destructuring args: ${args}`);
if (typeof args === "string") {
return args.split(",").map((arg) => arg.trim());
}
return Array.isArray(args) ? args : [args];
}
/**
* Retrieves the content of the last user message in the provided messages array.
* @param {Array<Object>} messagesArray - An array of message objects.
* @returns {string} The content of the last user message.
*/
function lastUserMessage(messages) {
if (!messages || !Array.isArray(messages)) {
logger.warn("lastUserMessage called with invalid messages array");
return "";
}
const userMessages = messages.filter((message) => message.role === "user");
return userMessages.length > 0
? userMessages[userMessages.length - 1].content
: "";
}
module.exports = {
countTokens,
countTokensInMessageArray,
removeMentionFromMessage,
splitAndSendMessage,
splitMessageIntoChunks,
destructureArgs,
parseJSONArg,
cleanUrlForPuppeteer,
sleep,
processChunks,
getConfigFromSupabase,
displayTypingIndicator,
getUniqueEmoji,
doesMessageContainCapability,
countMessageTokens,
// capabilityRegex,
lastUserMessage,
capabilityRegexGlobal,
capabilityRegexSingle,
};