Skip to content

Commit 923b0e3

Browse files
authored
Update index.ts
1 parent 5180df0 commit 923b0e3

File tree

1 file changed

+45
-50
lines changed

1 file changed

+45
-50
lines changed

src/index.ts

Lines changed: 45 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,6 @@ router.post('/send', async (request, env) => {
9898
}
9999
});
100100

101-
102101
router.post('/', async (request, env, ctx) => {
103102
const { isValid, interaction } = await verifyDiscordRequest(request, env);
104103
if (!isValid || !interaction) {
@@ -303,6 +302,7 @@ async function verifyDiscordRequest(request: any, env: any) {
303302
return { interaction: JSON.parse(body), isValid: true };
304303
}
305304

305+
// Process the role assignment in batches to handle large lists synchronously
306306
async function processRoleAssignment(
307307
interaction: any,
308308
env: any,
@@ -314,46 +314,40 @@ async function processRoleAssignment(
314314
let roleName = `Role ID ${roleId}`;
315315
let successList: string[] = [];
316316
let failureList: string[] = [];
317+
const batchSize = 10; // You can adjust the batch size as needed
317318

318319
try {
319320
// Fetch all roles from the server
320321
const roleResponse = await fetch(`https://discord.com/api/v9/guilds/${guildId}/roles`, {
321322
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
322323
});
323-
324324
if (!roleResponse.ok) {
325325
await updateOriginalMessage(interaction, env, '❌ Failed to fetch server roles.');
326326
return;
327327
}
328-
329328
const roles = await roleResponse.json();
330329
const targetRole = roles.find((r: any) => r.id === roleId);
331-
332330
if (!targetRole) {
333331
await updateOriginalMessage(interaction, env, '❌ The specified role does not exist.');
334332
return;
335333
}
336-
337334
roleName = targetRole.name;
338335

339336
// Fetch the issuer's roles
340337
const issuerResponse = await fetch(`https://discord.com/api/v9/guilds/${guildId}/members/${issuerId}`, {
341338
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
342339
});
343-
344340
if (!issuerResponse.ok) {
345341
await updateOriginalMessage(interaction, env, '❌ Failed to verify your roles.');
346342
return;
347343
}
348-
349344
const issuerData = await issuerResponse.json();
350345
const issuerRoles = issuerData.roles;
351346

352347
// Check if the role being assigned is higher than the issuer's highest role
353348
const issuerHighestRole = roles
354349
.filter((r: any) => issuerRoles.includes(r.id))
355350
.reduce((highest: any, role: any) => (role.position > highest.position ? role : highest), { position: 0 });
356-
357351
if (targetRole.position >= issuerHighestRole.position) {
358352
await updateOriginalMessage(
359353
interaction,
@@ -363,58 +357,59 @@ async function processRoleAssignment(
363357
return;
364358
}
365359

366-
for (const username of users) {
367-
try {
368-
// Fetch user ID by username using search endpoint
369-
const searchResponse = await fetch(
370-
`https://discord.com/api/v9/guilds/${guildId}/members/search?query=${username}`,
371-
{
372-
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
360+
// Process users in batches synchronously
361+
for (let i = 0; i < users.length; i += batchSize) {
362+
const batch = users.slice(i, i + batchSize);
363+
for (const username of batch) {
364+
try {
365+
// Fetch user ID by username using search endpoint
366+
const searchResponse = await fetch(
367+
`https://discord.com/api/v9/guilds/${guildId}/members/search?query=${username}`,
368+
{
369+
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
370+
}
371+
);
372+
if (!searchResponse.ok) {
373+
failureList.push(username);
374+
continue;
373375
}
374-
);
375-
376-
if (!searchResponse.ok) {
377-
failureList.push(username);
378-
continue;
379-
}
380-
381-
const members = await searchResponse.json();
382-
const user = members.find((m: any) => m.user.username.toLowerCase() === username.toLowerCase());
383-
384-
if (!user) {
385-
failureList.push(username);
386-
continue;
387-
}
388-
389-
// Add role to user
390-
const addRoleResponse = await fetch(
391-
`https://discord.com/api/v9/guilds/${guildId}/members/${user.user.id}/roles/${roleId}`,
392-
{
393-
method: "PUT",
394-
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
376+
const members = await searchResponse.json();
377+
const user = members.find((m: any) => m.user.username.toLowerCase() === username.toLowerCase());
378+
if (!user) {
379+
failureList.push(username);
380+
continue;
395381
}
396-
);
397-
398-
if (addRoleResponse.ok) {
399-
successList.push(username);
400-
} else {
382+
// Add role to user
383+
const addRoleResponse = await fetch(
384+
`https://discord.com/api/v9/guilds/${guildId}/members/${user.user.id}/roles/${roleId}`,
385+
{
386+
method: "PUT",
387+
headers: { 'Authorization': `Bot ${env.DISCORD_TOKEN}` }
388+
}
389+
);
390+
if (addRoleResponse.ok) {
391+
successList.push(username);
392+
} else {
393+
failureList.push(username);
394+
}
395+
} catch (error) {
401396
failureList.push(username);
402397
}
403-
} catch (error) {
404-
failureList.push(username);
405398
}
399+
// Update progress after processing each batch
400+
const progressMessage = `Processing roles...\n✅ Added: ${successList.join(', ')}\n❌ Failed: ${failureList.join(', ')}\nProcessed ${Math.min(i + batchSize, users.length)} of ${users.length}`;
401+
await updateOriginalMessage(interaction, env, progressMessage);
406402
}
407-
408-
// Construct final response message.
409-
let responseMessage = '';
403+
404+
// Final update message
405+
let finalMessage = '';
410406
if (successList.length > 0) {
411-
responseMessage += `✅ **${roleName}** added to: ${successList.join(', ')}\n`;
407+
finalMessage += `✅ **${roleName}** added to: ${successList.join(', ')}\n`;
412408
}
413409
if (failureList.length > 0) {
414-
responseMessage += `❌ Failed to add **${roleName}** to: ${failureList.join(', ')}`;
410+
finalMessage += `❌ Failed to add **${roleName}** to: ${failureList.join(', ')}`;
415411
}
416-
417-
await updateOriginalMessage(interaction, env, responseMessage);
412+
await updateOriginalMessage(interaction, env, finalMessage);
418413
} catch (error: any) {
419414
await updateOriginalMessage(interaction, env, `❌ An error occurred: ${error.message}`);
420415
}

0 commit comments

Comments
 (0)