|
| 1 | +import { env } from "../typeDefinitions/default.types"; |
| 2 | +import { DISCORD_BASE_URL } from "../constants/urls"; |
| 3 | +import { |
| 4 | + parseRateLimitRemaining, |
| 5 | + parseResetAfter, |
| 6 | +} from "./batchDiscordRequests"; |
| 7 | +import { |
| 8 | + discordMessageRequest, |
| 9 | + discordMessageError, |
| 10 | +} from "../typeDefinitions/discordMessage.types"; |
| 11 | + |
| 12 | +export async function removeUsers( |
| 13 | + env: env, |
| 14 | + usersWithMatchingRole: string[], |
| 15 | + channelId: number |
| 16 | +) { |
| 17 | + const batchSize = 4; |
| 18 | + let waitTillNextAPICall = 0; |
| 19 | + |
| 20 | + try { |
| 21 | + const failedUsers: Array<string> = []; |
| 22 | + for (let i = 0; i < usersWithMatchingRole.length; i += batchSize) { |
| 23 | + const batchwiseUsers = usersWithMatchingRole.slice(i, i + batchSize); |
| 24 | + const deleteRequests = batchwiseUsers.map((mention) => { |
| 25 | + const userId = mention.replace(/<@!*/g, "").replace(/>/g, ""); |
| 26 | + const url = `${DISCORD_BASE_URL}/guilds/${env.DISCORD_GUILD_ID}/members/${userId}`; |
| 27 | + |
| 28 | + return fetch(url, { |
| 29 | + method: "DELETE", |
| 30 | + headers: { |
| 31 | + "Content-Type": "application/json", |
| 32 | + Authorization: `Bot ${env.DISCORD_TOKEN}`, |
| 33 | + }, |
| 34 | + }).then((response) => { |
| 35 | + const rateLimitRemaining = parseRateLimitRemaining(response); |
| 36 | + if (rateLimitRemaining === 0) { |
| 37 | + waitTillNextAPICall = Math.max( |
| 38 | + parseResetAfter(response), |
| 39 | + waitTillNextAPICall |
| 40 | + ); |
| 41 | + } |
| 42 | + return response.json(); |
| 43 | + }) as Promise<discordMessageRequest | discordMessageError>; |
| 44 | + }); |
| 45 | + |
| 46 | + const responses = await Promise.all(deleteRequests); |
| 47 | + responses.forEach((response, i) => { |
| 48 | + if (response && "message" in response) { |
| 49 | + failedUsers.push(batchwiseUsers[i]); |
| 50 | + console.error(`Failed to remove a user`); |
| 51 | + } |
| 52 | + }); |
| 53 | + await sleep(waitTillNextAPICall * 1000); |
| 54 | + waitTillNextAPICall = 0; |
| 55 | + } |
| 56 | + |
| 57 | + if (failedUsers.length > 0) { |
| 58 | + await fetch(`${DISCORD_BASE_URL}/channels/${channelId}/messages`, { |
| 59 | + method: "POST", |
| 60 | + headers: { |
| 61 | + "Content-Type": "application/json", |
| 62 | + Authorization: `Bot ${env.DISCORD_TOKEN}`, |
| 63 | + }, |
| 64 | + body: JSON.stringify({ |
| 65 | + content: `Failed to remove ${failedUsers}.`, |
| 66 | + }), |
| 67 | + }); |
| 68 | + } |
| 69 | + } catch (error) { |
| 70 | + console.error("Error occurred while removing users:", error); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +function sleep(ms: number) { |
| 75 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 76 | +} |
0 commit comments