-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.js
759 lines (683 loc) · 27.6 KB
/
functions.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
/* eslint-disable no-unused-vars */
// eslint-disable no-undef
const { Client, EmbedBuilder, Interaction, ActionRow, ButtonComponent, SelectMenuComponent, SelectMenuInteraction, SelectMenuOptionBuilder, ComponentType, ActionRowBuilder, ButtonStyle, ButtonBuilder, User } = require("discord.js");
const { default: fetch } = require("node-fetch");
const config = require("./config.json");
const fs = require("fs");
const path = require("path");
const {promisify} = require("util");
const errors = {
"[SQL-ERR]": "An error has occurred while communicating with the database",
"[ERR-CLD]": "You are on cooldown!",
"[ERR-UPRM]": "You do not have the proper permissions to execute this command",
"[ERR-BPRM]": "This bot does not have proper permissions to execute this command",
"[ERR-ARGS]": "You have not supplied the correct parameters. Please check again",
"[ERR-UNK]": "An unknwon error occurred. Please report this to a developer",
"[ERR-MISS]": "The requested information wasn't found",
"[WARN-NODM]": "This command isn't available in Direct Messages. Please run this in a server",
"[WARN-CMD]": "The requested slash command was not found. Please refresh your Discord client and try again",
"[INFO-DEV]": "This command is in development. This should not be expected to work"
};
/**
* @typedef RobloxGroupUserData
* @prop {RobloxGroupGroupData} group
* @prop {RobloxGroupRoleData} role
*/
/**
* @typedef {Object} RobloxGroupGroupData
* @prop {string} id Group ID
* @prop {string} name Name of the group
* @prop {number} memberCount Member count of the group
*/
/**
* @typedef {Object} RobloxGroupRoleData
* @prop {number} id Numeric identifier of the role
* @prop {string} name Name of the role
* @prop {string} rank Rank of the role (0-255)
*/
/**
* @description Sends a message to the console
* @param {String} message [REQUIRED] The message to send to the console
* @param {String} source [REQUIRED] Source of the message
* @param {Client} client [REQUIRED] A logged-in Client to send the message
* @returns {null} null
* @example toConsole(`Hello, World!`, `functions.js 12:15`, client);
* @example toConsole(`Published a ban`, `ban.js 14:35`, client);
*/
const toConsole = async (message, source, client) => {
if (!message || !source || !client) return console.error(`One or more of the required parameters are missing.\n\n> message: ${message}\n> source: ${source}\n> client: ${client}`);
const channel = await client.channels.cache.get(config.logchannelid);
if (!channel) return console.warn("[WARN] toConsole called but bot cannot find config.logchannelid", message, source);
console.log(message);
source = new RegExp(/(at.+\(.+\)|at .+[\\/].+\.js:.+)/).exec(source)[0];
// eslint-disable-next-line no-useless-escape
source = source.replace("at ", "").replace(/\(?.+[\\/]/, "").replace(")", "").replace(":", "\:");
console.debug(source);
channel.send(`Incoming message from ${source} at <t:${Math.floor(Date.now() / 1000)}:F>`);
channel.send({
embeds: [
new EmbedBuilder({
title: "Message to Console",
color: 0xFF0000,
description: message || "",
footer: {
text: `Source: ${source} @ ${new Date().toLocaleTimeString()} ${new Date().toString().match(/GMT([+-]\d{2})(\d{2})/)[0]}`
},
timestamp: new Date()
})
]
});
return null;
};
/**
* @description Replies with a EmbedBuilder to the Interaction
* @param {Number} type 1- Sucessful, 2- Warning, 3- Error, 4- Information
* @param {String} content The information to state
* @param {String} expected The expected argument (If applicable)
* @param {Interaction} interaction The Interaction object for responding
* @param {Client} client Client object for logging
* @param {Array<Boolean, Number>} remove Whether to delete the message and the specified timeout in seconds
* @example interactionEmbed(1, `Removed ${removed} roles`, ``, interaction, client, [false, 0])
* @example interactionEmbed(3, `[ERR-UPRM]`, `Missing: \`Manage Messages\``, interaction, client, [true, 15])
* @returns {null}
*/
const interactionEmbed = async function (type, content, expected, interaction, client, remove) {
if (!type || typeof content != "string" || expected === undefined || !interaction || !client || !remove || remove.length != 2) throw new SyntaxError(`One or more of the required parameters are missing in [interactionEmbed]\n\n> ${type}\n> ${content}\n> ${expected}\n> ${interaction}\n> ${client}`);
if (!interaction.deferred) await interaction.deferReply();
const embed = new EmbedBuilder();
switch (type) {
case 1:
embed
.setTitle("Success")
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.avatarURL({ dynamic: true, size: 4096 }) })
.setColor(0x5865F2)
.setDescription(!errors[content] ? expected : `${errors[content]}\n> ${expected}`)
.setTimestamp();
break;
case 2:
embed
.setTitle("Warning")
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.avatarURL({ dynamic: true, size: 4096 }) })
.setColor(0xFEE75C)
.setDescription(!errors[content] ? expected : `${errors[content]}\n> ${expected}`)
.setTimestamp();
break;
case 3:
embed
.setTitle("Error")
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.avatarURL({ dynamic: true, size: 4096 }) })
.setColor(0xFF0000)
.setDescription(!errors[content] ? `I don't understand the error "${content}" but was expecting ${expected}. Please report this to the support server!` : `${errors[content]}\n> ${expected}`)
.setTimestamp();
break;
case 4:
embed
.setTitle("Information")
.setAuthor({ name: interaction.user.username, iconURL: interaction.user.avatarURL({ dynamic: true, size: 4096 }) })
.setColor(0x5865F2)
.setDescription(!errors[content] ? expected : `${errors[content]}\n> ${expected}`)
.setTimestamp();
break;
}
await interaction.editReply({ content: "", embeds: [embed] });
if (remove[0]) setTimeout(() => { interaction.deleteReply(); }, remove[1] * 1000);
return null;
};
/**
* Sends buttons to a user and awaits the response
* @param {Interaction} interaction Interaction object
* @param {Number} time Seconds for which the buttons are valid
* @param {Array<ButtonComponent>} buttons The buttons to place on the message
* @param {String|null} content The content to display, can be blank
* @param {Boolean} remove Delete the message after the time expires
* @example awaitButtons(interaction, 15, [button1, button2], `Select a button`, true);
* @returns {ButtonComponent|null} The button the user clicked or null if no button was clicked
*/
const awaitButtons = async function (interaction, time, buttons, content, remove) {
if (!interaction || !time || !buttons || remove === null) return new SyntaxError(`One of the following values is not fulfilled:\n> interaction: ${interaction}\n> time: ${time}\n> buttons: ${buttons}\n> remove: ${remove}`);
content = content ?? "Please select an option";
// Create a filter
const filter = i => {
return i.user.id === interaction.user.id;
};
// Convert the time to milliseconds
time *= 1000;
// Create a ActionRow and add the buttons
const row = new ActionRow();
row.addComponents(buttons);
// Send a follow-up message with the buttons and await a response
const message = await interaction.followUp({ content: content, components: [row] });
const res = await message
.awaitMessageComponent({ filter, componentType: ComponentType.Button, time: time, errors: ["time"] })
.catch(() => { return null; });
// Disable the buttons on row
for (const button of row.components) {
button.setDisabled(true);
}
// Step 5: Cleanup
setTimeout(() => {
if (message != undefined && remove && res != null) message.delete();
}, 1500);
await message.edit({ content: content, components: [] });
return res;
};
/**
* Send a SelectMenuComponent to a user and awaits the response
* @param {Interaction} interaction Interaction object
* @param {Number} time Seconds for which the menu is valid
* @param {Number[]} values [min, max] The amount of values that can be selected
* @param {SelectMenuOptionBuilder|SelectMenuOptionBuilder[]} options The options for the menu
* @param {String|null} content The content to display, can be blank
* @param {Boolean} remove Delete the message after the time expires
* @example awaitMenu(interaction, 15, [menu], `Select an option`, true);
* @returns {SelectMenuInteraction|null} The menu the user interacted with or null if nothing was selected
*/
const awaitMenu = async function (interaction, time, values, options, content, remove) {
// Step 0: Checks
if (!interaction || !time || !values || !options || remove === null) return new SyntaxError(`One of the following values is not fulfilled:\n> interaction: ${interaction}\n> time: ${time}\n> values: ${values}\n> options: ${options}\n> remove: ${remove}`);
content = content ?? "Please select an option";
// Step 1: Setup
const filter = i => {
return i.user.id === interaction.user.id;
};
time *= 1000;
// Step 2: Creation
const row = new ActionRow();
const menu = new SelectMenuComponent({
minValues: values[0],
maxValues: values[1],
customId: "await-menu"
});
menu.addOptions(options);
row.addComponents(menu);
// Step 3: Execution
const message = await interaction.followUp({ content: content, components: [row] });
const res = await message
.awaitMessageComponent({ filter, componentType: ComponentType.SelectMenu, time: time, errors: ["time"] })
.catch(() => { return null; });
// Step 4: Processing
row.components[0].setDisabled(true);
// eslint-disable-next-line no-useless-escape
await message.edit({ content: res === null ? "\:lock: Cancelled" : content, components: [row] });
// Step 5: Cleanup
setTimeout(() => {
if (message != undefined && remove && res != null) message.delete();
}, 1500);
await message.edit({ content: content, components: [] });
return res;
};
/**
* Fetches Roblox user data by username or user ID.
* @async
* @param {string | number} input - Roblox username or user ID.
* @returns {Promise<{ success: boolean, error?: string, user?: object }>} - The result of the fetch operation.
*/
async function getRoblox(input) {
if (!isNaN(Number(input))) {
// If input is a number, fetch the user from Roblox API
const resp = await fetch(`https://users.roblox.com/v1/users/${input}`);
const user = await resp.json().catch(() => ({ errors: [] }));
// If the user is not found or rate limited, return an error
if (resp.status === 429) {
return {
success: false,
error: "Ratelimited by Roblox. Try again later or visit the user's profile manually for their user ID"
};
}
if (user.errors) {
return { success: false, error: `Interpreted ${input} as user ID but found no user` };
}
// Return the user
return { success: true, user };
} else {
const resp = await fetch('https://users.roblox.com/v1/usernames/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ usernames: [input] })
});
const user = await resp
.json()
.then(r => r.data[0])
.catch(() => null);
// If the user is not found or rate limited, return an error
if (resp.status === 429) {
return {
success: false,
error: "Ratelimited by Roblox. Try again later or visit the user's profile manually for their user ID"
};
}
if (!user) {
return { success: false, error: `Interpreted ${input} as username but found no user` };
}
// Return the user
return { success: true, user };
}
};
/**
* Gets the key of an enum object by its value.
* @param {object} enumObj - The enum object.
* @param {number} value - The value to look up.
* @returns {string | undefined} - The key corresponding to the value.
*/
function getEnumKey(enumObj, value) {
for (const key in enumObj) {
if (Object.prototype.hasOwnProperty.call(enumObj, key) && enumObj[key] === value) {
return key;
}
}
return undefined;
};
/**
* @async
* @param {string} username Roblox username
* @param {number} groupId Group ID to fetch
* @returns {{success: boolean, error: string}|RobloxGroupUserData}
*/
const getGroup = async (username, groupId) => {
if (!groupId) return { success: false, error: "No group ID provided" };
if (isNaN(username)) {
const user = await fetch(`https://api.roblox.com/users/get-by-username?username=${username}`)
.then(res => res.json());
if (user.success) return { success: false, error: `Interpreted \`${username}\` as Username but no user was found` };
username = user.Id;
} else {
const user = await fetch(`https://api.roblox.com/users/${username}`)
.then(res => res.json());
if (user.success) return { success: false, error: `Interpreted \`${username}\` as ID but no user was found` };
}
const group = await fetch(`https://groups.roblox.com/v2/users/${username}/groups/roles`)
.then(res => res.json());
if (group.errorMessage) return { success: false, error: `No group found with ID \`${groupId}\`` };
const role = group.data.find(g => g.group.id === groupId);
if (!role) return { success: false, error: "User is not in the group specified" };
return { success: true, data: role };
};
/**
* @async
* @param {number|string} user Discord user ID
* @param {Client} client Discord client
* @returns {{success: false, error?: string}|{success: true, roblox: string, username: string}}
*/
const getRowifi = async (user, client) => {
if (!user) return { success: false, error: "No username provided" };
const userData = await fetch(`https://api.rowifi.xyz/v2/guilds/${config.mainServer}/members/${user}`, { headers: { "Authorization": `Bot ${config.rowifiApiKey}` } })
.then(res => {
if (!res.ok) {
if (res.status !== 404) module.exports.toConsole(`Rowifi API returned ${res.status} ${res.statusText}`, new Error().stack, client);
return { success: false };
} else
return res.json();
});
if (userData.success !== undefined) return { success: false, error: "Rowifi failed to return any data! (If you are signed in with Rowifi, report this to a developer)" };
const roblox = await fetch(`https://users.roblox.com/v1/users/${userData.roblox_id}`)
.then(res => res.json());
if (roblox.errors) return { success: false, error: "Roblox ID does not exist" };
return { success: true, roblox: userData.roblox_id.toString(), username: roblox.name };
};
/**
* @param {String} time
* @returns {Number|"NaN"}
*/
const parseTime = function (time) {
let duration = 0;
if (!time.match(/[1-9]{1,3}[dhms]/g)) return "NaN";
for (const period of time.match(/[1-9]{1,3}[dhms]/g)) {
const [amount, unit] = period.match(/^(\d+)([dhms])$/).slice(1);
duration += unit === "d" ? amount * 24 * 60 * 60 : unit === "h" ? amount * 60 * 60 : unit === "m" ? amount * 60 : amount;
}
return duration;
};
/**
* @param {interaction} interaction
* @param {embeds} embeds
*/
const paginationEmbed = async function (interaction, embeds) {
let allbuttons = new ActionRowBuilder().addComponents([
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId("1").setLabel("◀"),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId("2").setLabel("❌"),
new ButtonBuilder().setStyle(ButtonStyle.Secondary).setCustomId("3").setLabel("▶"),
]);
if (embeds.length === 1) {
if (interaction.deferred) {
return interaction.followUp({
embeds: [embeds[0]],
});
} else {
return interaction.reply({
embeds: [embeds[0]],
fetchReply: true,
});
}
}
embeds = embeds.map((embed, index) => {
return embed.setFooter({
text: `Page ${index + 1}/${embeds.length}`,
iconURL: interaction.guild.iconURL({ dynamic: true }),
});
});
let sendMsg;
if (interaction.deferred) {
sendMsg = await interaction.followUp({
embeds: [embeds[0]],
components: [allbuttons],
});
} else {
sendMsg = await interaction.reply({
embeds: [embeds[0]],
components: [allbuttons],
});
}
let filter = (m) => m.member.id === interaction.member.id;
const collector = await sendMsg.createMessageComponentCollector({
filter: filter,
time: 30000,
});
let currentPage = 0;
collector.on("collect", async (b) => {
if (b.isButton()) {
await b.deferUpdate().catch((e) => null);
// page first
switch (b.customId) {
case "1":
{
if (currentPage != 0) {
currentPage -= 1;
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
} else {
currentPage = embeds.length - 1;
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
}
}
break;
case "2":
{
allbuttons.components.forEach((btn) => btn.setDisabled(true));
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
}
break;
case "3":
{
if (currentPage < embeds.length - 1) {
currentPage++;
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
} else {
currentPage = 0;
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
}
}
break;
default:
break;
}
}
});
collector.on("end", async () => {
allbuttons.components.forEach((btn) => btn.setDisabled(true));
await sendMsg
.edit({
embeds: [embeds[currentPage]],
components: [allbuttons],
})
.catch((e) => null);
});
};
/**
* @description Returns the full payload from a Roblox endpoint that returns an object like the following {data:{whatever: "whatever"}}
* @param {String} url URL to fetch from
* @param {Object} options Options to pass to node-fetch
* @returns {{success:false,error:string}|{success:true,payload:Object}}
*/
const paginationResponses = async function (url, options) {
const resp = await fetch(url, options)
.then(res => res.json());
if (resp.errors) return { success: false, error: resp.errors[0].message };
const rawPayloads = [resp];
let cursor = resp.nextPageCursor;
while (cursor) {
const newResp = await fetch(`${url}&cursor=${cursor}`, options)
.then(res => res.json());
rawPayloads.push(newResp);
cursor = newResp.nextPageCursor;
}
// Merge all the payloads into one
const payload = rawPayloads.reduce((acc, cur) => {
acc.data = acc.data.concat(cur.data);
return acc;
});
return { success: true, payload };
};
/**
* Retrieves group information for a user by their userId.
* @param {number} userId - The userId of the user.
* @param {number} groupId - The groupId of the group.
* @returns {{
* success: boolean,
* data?: { group: { id: number, name: string, memberCount: number, hasVerifiedBadge: boolean }, role: { id: number, name: string, rank: number } },
* error?: string
* }} An object indicating the success or failure of the operation, along with relevant data or error message.
*/
const getGroupByUserId = async function (userId, groupId) {
if (!groupId) return { success: false, error: "No group ID provided" };
// Check if userId is a number
if (isNaN(userId)) {
return { success: false, error: "User ID must be a number" };
}
const group = await fetch(`https://groups.roblox.com/v2/users/${userId}/groups/roles`)
.then(res => res.json());
if (group.errorMessage) return { success: false, error: `No group found with ID \`${groupId}\`` };
const role = group.data.find(g => g.group.id === groupId);
if (!role) return { success: false, error: "User is not in the group specified" };
return { success: true, data: role };
};
/**
* Extracts Discord user IDs from a given text.
* @param {string} text - The text to extract user IDs from.
* @returns {string[]} An array containing the extracted user IDs.
*/
const extractIDs = function (text) {
const pattern = /<@(\d+)>/g;
const ids = [];
let match;
while ((match = pattern.exec(text))) {
ids.push(match[1]);
}
return ids;
};
/**
* Fetches user information from Roblox API based on provided usernames.
* @param {string[]} usernames Array of usernames to fetch user information for.
* @returns {Promise<{
* users: {
* id: string,
* username: string,
* displayName: string
* }[],
* error: string|null,
* success: boolean
* }>} Object containing user information, error message (if any), and success status.
*/
const fetchUserInformationFromUsernames = async (usernames) => {
try {
const response = await fetch("https://users.roblox.com/v1/usernames/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
usernames: usernames,
excludeBannedUsers: false
})
});
const data = await response.json();
if (data.errors && data.errors.length > 0) {
const errorMessages = data.errors.map(error => {
const code = error.code || "Unknown";
const message = error.message || "Unknown error occurred.";
const userFacingMessage = error.userFacingMessage || "Unknown";
return `Code: ${code}. Message: ${message}. UserFacingMessage: ${userFacingMessage}`;
});
return {
users: [],
error: `Errors occurred: ${errorMessages.join("; ")}`,
success: false
};
}
return {
users: data.data.map(user => ({
id: user.id,
username: user.name,
displayName: user.displayName
})),
error: null,
success: true
};
} catch (error) {
console.error("Error fetching user information:", error);
return {
users: [],
error: `Failed to fetch user information. ${error}`,
success: false
};
}
};
/**
* Returns an array of roblox info from inputted Roblox usernames and Discord mentions. Needs Rowifi
* @param input: string
* @param interaction: CommandInteraction
* @param client: Client
* @returns {Promise<{
* users:
* {
* id: string,
* username: string,
* discord: User | null
* }[]|null,
* error: string|null,
* success: boolean
* }>}
*/
const getRobloxInfoFromDiscordMentionsOrRobloxUsernames = async function(input, interaction, client)
{
/**
* @type {{
* id: string,
* username: string,
* discord: Object | null
* }[]}
*/
const result = [];
const exploded = input.split(" ");
const robloxUsernames = [];
const unresolvedUsers = [];
for (const explosion of exploded) {
// remove anything that is not a letter, number or underscore
let probableUser = explosion.trim().replace(/[^a-zA-Z0-9_]/g, "");
//check whether the string is a number or not
if (!isNaN(parseInt(probableUser))) {
// if probableUser is a number, check whether that's a Discord user
var member = null;
try{
member = await interaction.guild.members.fetch(probableUser);
} catch (e)
{
// if the number is not a discord user id, push it to unresolved users since it can be a roblox username (in the past, roblox usernames could be numbers only)
robloxUsernames.push(probableUser);
}
if(member) {
let rowifiProbableUserResult = await getRowifi(probableUser, client);
if (!rowifiProbableUserResult.success) {
return {success: false, users:[], error: `Seems like <@${probableUser}> is not verified with RoWifi or is not in the server. Ensure each subject is verified and in your server when requesting with Discord mentions. You can still use Roblox usernames regardless of being in the server/RoWifi verification \nError: ${rowifiProbableUserResult.error}`};
} else {
// if correctly resolved by RoWifi, push to the results
result.push({
id: `${rowifiProbableUserResult.roblox}`,
username: rowifiProbableUserResult.username,
discord: member.user
});
}
}
} else {
// if the input is not a number, push it to roblox usernames
robloxUsernames.push(probableUser);
}
}
const robloxUserObjectsResult = await fetchUserInformationFromUsernames(robloxUsernames);
if (!robloxUserObjectsResult.success) {
return {success: false, error: `Error occurred when processing Roblox usernames. Ensure correct usernames are provided. \nError: ${robloxUserObjectsResult.error}`, users: []};
}
robloxUserObjectsResult.users.forEach((user) => {
result.push({id: user.id.toString(), username: user.username, discord: null});
});
return {users: result, success: true, error: null};
};
/**
* Retrieves the count of friends for a user by their userId.
* @param {string} userId - The userId of the user.
* @returns {{
* success: boolean,
* count?: number,
* error?: string
* }} An object indicating the success or failure of the operation, along with relevant data or error message.
*/
const getFriendsCount = async function(userId) {
// Check if userId is a number
if (isNaN(userId)) {
return { success: false, error: "User ID must be a number" };
}
try {
const response = await fetch(`https://friends.roblox.com/v1/users/${userId}/friends/count`);
const data = await response.json();
if (data.errors) {
return { success: false, error: data.errors[0].userFacingMessage || "Something went wrong" };
}
if (!data.count && data.count !== 0) {
return { success: false, error: "Count of friends not found in the response" };
}
return { success: true, count: data.count };
} catch (error) {
return { success: false, error: "Failed to fetch friends count: " + error.message };
}
};
module.exports = {
fetchUserInformationFromUsernames,
toConsole,
extractIDs,
awaitButtons,
awaitMenu,
getRowifi,
getGroup,
getRoblox,
getEnumKey,
paginationEmbed,
paginationResponses,
parseTime,
getRobloxInfoFromDiscordMentionsOrRobloxUsernames,
getGroupByUserId,
getFriendsCount,
interactionEmbed
};