@@ -4,12 +4,21 @@ import {
4
4
parseRateLimitRemaining ,
5
5
parseResetAfter ,
6
6
} from "./batchDiscordRequests" ;
7
+ import {
8
+ discordMessageRequest ,
9
+ discordMessageError ,
10
+ } from "../typeDefinitions/discordMessage.types" ;
7
11
8
- export async function removeUsers ( env : env , usersWithMatchingRole : string [ ] ) {
12
+ export async function removeUsers (
13
+ env : env ,
14
+ usersWithMatchingRole : string [ ] ,
15
+ channelId : number
16
+ ) {
9
17
const batchSize = 4 ;
10
18
let waitTillNextAPICall = 0 ;
11
19
12
20
try {
21
+ const failedUsers : Array < string > = [ ] ;
13
22
for ( let i = 0 ; i < usersWithMatchingRole . length ; i += batchSize ) {
14
23
const batchwiseUsers = usersWithMatchingRole . slice ( i , i + batchSize ) ;
15
24
const deleteRequests = batchwiseUsers . map ( ( mention ) => {
@@ -22,32 +31,41 @@ export async function removeUsers(env: env, usersWithMatchingRole: string[]) {
22
31
"Content-Type" : "application/json" ,
23
32
Authorization : `Bot ${ env . DISCORD_TOKEN } ` ,
24
33
} ,
25
- } ) . then ( async ( response ) => {
34
+ } ) . then ( ( response ) => {
26
35
const rateLimitRemaining = parseRateLimitRemaining ( response ) ;
27
-
28
36
if ( rateLimitRemaining === 0 ) {
29
37
waitTillNextAPICall = Math . max (
30
38
parseResetAfter ( response ) ,
31
39
waitTillNextAPICall
32
40
) ;
33
41
}
34
-
35
- // Check if response status is 204 (No Content) indicating success
36
- if ( response . status === 204 ) {
37
- return { success : true } ;
38
- } else {
39
- throw new Error ( `Failed to remove user ${ userId } .` ) ;
40
- }
41
- } ) ;
42
+ return response . json ( ) ;
43
+ } ) as Promise < discordMessageRequest | discordMessageError > ;
42
44
} ) ;
43
45
44
- // Wait for all delete requests in the batch to complete
45
- await Promise . all ( deleteRequests ) ;
46
-
47
- // Wait until the next API call is allowed based on rate limits
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
+ } ) ;
48
53
await sleep ( waitTillNextAPICall * 1000 ) ;
49
54
waitTillNextAPICall = 0 ;
50
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
+ }
51
69
} catch ( error ) {
52
70
console . error ( "Error occurred while removing users:" , error ) ;
53
71
}
0 commit comments