forked from JaredScar/Badger_Discord_API
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.lua
More file actions
680 lines (632 loc) · 22.8 KB
/
Copy pathserver.lua
File metadata and controls
680 lines (632 loc) · 22.8 KB
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
local FormattedToken = "Bot " .. Config.Bot_Token
local error_codes_defined = {
[200] = 'OK - The request was completed successfully..!',
[400] = "Error - The request was improperly formatted, or the server couldn't understand it..!",
[401] = 'Error - The Authorization header was missing or invalid..! Your Discord Token is probably wrong or does not have correct permissions attributed to it.',
[403] = 'Error - The Authorization token you passed did not have permission to the resource..! Your Discord Token is probably wrong or does not have correct permissions attributed to it.',
[404] = "Error - The resource at the location specified doesn't exist.",
[429] = 'Error - Too many requests, you hit the Discord rate limit. https://discord.com/developers/docs/topics/rate-limits',
[502] = 'Error - Discord API may be down?...'
};
Citizen.CreateThread(function()
if (GetCurrentResourceName() ~= "Badger_Discord_API") then
--StopResource(GetCurrentResourceName());
print("[" .. GetCurrentResourceName() .. "] " .. "IMPORTANT: This resource must be named Badger_Discord_API for it to work properly with other scripts...");
end
end)
tracked = {}
card = [[
{
"type": "AdaptiveCard",
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.4",
"body": [
{
"type": "Image",
"url": "]] .. Config.Splash.Header_IMG .. [[",
"horizontalAlignment": "Center"
},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Badger_Discord_API",
"wrap": true,
"fontType": "Default",
"size": "ExtraLarge",
"weight": "Bolder",
"color": "Light",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"text": "]] .. Config.Splash.Heading1 .. [[",
"wrap": true,
"size": "Large",
"weight": "Bolder",
"color": "Light",
"horizontalAlignment": "Center"
},
{
"type": "TextBlock",
"text": "]] .. Config.Splash.Heading2 .. [[",
"wrap": true,
"color": "Light",
"size": "Medium",
"horizontalAlignment": "Center"
},
{
"type": "ColumnSet",
"height": "stretch",
"minHeight": "100px",
"bleed": true,
"horizontalAlignment": "Center",
"columns": [
{
"type": "Column",
"width": "stretch",
"items": [
{
"type": "ActionSet",
"actions": [
{
"type": "Action.OpenUrl",
"title": "Discord",
"url": "]] .. Config.Splash.Discord_Link .. [[",
"style": "positive"
}
],
"horizontalAlignment": "Right"
}
],
"height": "stretch"
},
{
"type": "Column",
"width": "stretch",
"items": [
{
"type": "ActionSet",
"actions": [
{
"type": "Action.OpenUrl",
"title": "Website",
"style": "positive",
"url": "]] .. Config.Splash.Website_Link .. [["
}
],
"horizontalAlignment": "Left"
}
]
}
]
}
],
"style": "default",
"bleed": true,
"height": "stretch"
}
]
}]]
if Config.Splash.Enabled then
AddEventHandler('playerConnecting', function(name, setKickReason, deferrals)
-- Player is connecting
deferrals.defer();
local src = source;
local toEnd = false;
local count = 0;
while not toEnd do
deferrals.presentCard(card,
function(data, rawData)
end)
Wait((1000))
count = count + 1;
if count == Config.Splash.Wait then
toEnd = true;
end
end
deferrals.done();
end)
end
function GetIdentifier(source, id_type)
if type(id_type) ~= "string" then return print('Invalid usage') end
for _, identifier in pairs(GetPlayerIdentifiers(source)) do
if string.find(identifier, id_type) then
return identifier
end
end
return nil
end
function GetGuildId (guildName)
local result = Config.Guild_ID
if guildName and Config.Guilds[guildName] then
result = tostring(Config.Guilds[guildName])
end
return result
end
function DiscordRequest(method, endpoint, jsondata, reason)
local data = nil
PerformHttpRequest("https://discordapp.com/api/"..endpoint, function(errorCode, resultData, resultHeaders)
data = {data=resultData, code=errorCode, headers=resultHeaders}
end, method, #jsondata > 0 and jsondata or "", {["Content-Type"] = "application/json", ["Authorization"] = FormattedToken, ['X-Audit-Log-Reason'] = reason})
while data == nil do
Citizen.Wait(0)
end
return data
end
function GetRoleIdFromRoleName(name, guild --[[optional]])
local guildId = GetGuildId(guild)
if (Caches.RoleList[guildId] ~= nil) then
return tonumber(Caches.RoleList[guildId][name]);
else
local roles = GetGuildRoleList(guild);
return tonumber(roles[name]);
end
end
function FetchRoleID(roleID2Check, guild --[[optional]])
-- You gave me an ID, here it is back to you.
if type(roleID2Check) == "number" then return roleID2Check end
-- You gave me a non-string, non-number. I can't help you.
if type(roleID2Check) ~= "string" then return nil end
if type(roleID2Check) == "string" then
if (tonumber(roleID2Check) ~= nil) then
return tonumber(roleID2Check);
end
end
-- It's a string, therefore name -- search config rolelist
local rolesListFromConfig = Config.RoleList
if rolesListFromConfig[roleID2Check] then
-- It's a named role in the config. Here you go!
return tonumber(rolesListFromConfig[roleID2Check])
end
-- Oops, didn't find in config rolelist, search by name in current guild
if (guild ~= nil) then
local fetchedRolesList = GetGuildRoleList(guild)
if fetchedRolesList[roleID2Check] then
-- We found it in the current guild. Here you go!
return tonumber(fetchedRolesList[roleID2Check])
end
end
-- Okay, still no luck. Search Main guild for role by name (if main isn't current guild)
if GetGuildId(guild) ~= tostring(Config.Guild_ID) then
local mainRolesList = GetGuildRoleList()
if mainRolesList[roleID2Check] then
-- We found it in the current guild. Here you go!
return tonumber(mainRolesList[roleID2Check])
end
end
-- Big oops, didn't find in current guild, or main guild. Search by name in all guilds!
--[[
-- Due to a security flaw in the below code, it was redacted for good reason...
if (Config.Multiguild and not roleFound) then
for guildName, guildID in pairs(Config.Guilds) do
local thisRolesList = GetGuildRoleList(guildName)
if thisRolesList[roleID2Check] then
-- We found it in the current guild. Here you go!
return tonumber(thisRolesList[roleID2Check])
end
end
end
]]--
return nil -- Sorry, couldn't find anywhere
end
function CheckEqual(role1, role2, guild --[[optional]])
local roleID1 = FetchRoleID(role1, guild);
local roleID2 = FetchRoleID(role2, guild);
if (Config.DebugScript) then
print("[Badger_Discord_API] role1: " .. tostring(role1));
print("[Badger_Discord_API] role2: " .. tostring(role2));
print("[Badger_Discord_API] roleID1 type: " .. type(roleID1));
print("[Badger_Discord_API] roleID2 type: " .. type(roleID2));
print("[Badger_Discord_API] roleID1: " .. tostring(roleID1));
print("[Badger_Discord_API] roleID2: " .. tostring(roleID2));
end
if (type(roleID1) ~= "nil" and type(roleID2) ~= "nil") and roleID1 == roleID2 then
return true
end
return false
end
function IsDiscordEmailVerified(user)
local discordId = nil
local isVerified = false;
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break
end
end
if discordId then
local endpoint = ("users/%s"):format(discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
if data ~= nil then
-- It is valid data
--print("The data for User " .. GetPlayerName(user) .. " is: ");
--print(data.avatar);
isVerified = data.verified;
--print("---")
end
else
print("[Badger_Perms] ERROR: Code 200 was not reached. DETAILS: " .. error_codes_defined[member.code]);
end
end
return isVerified;
end
function GetDiscordEmail(user)
local discordId = nil
local emailData = nil;
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break
end
end
if discordId then
local endpoint = ("users/%s"):format(discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
if data ~= nil then
-- It is valid data
--print("The data for User " .. GetPlayerName(user) .. " is: ");
--print(data.avatar);
emailData = data.email;
--print("---")
end
else
print("[Badger_Perms] ERROR: Code 200 was not reached. DETAILS: " .. error_codes_defined[member.code])
end
end
return emailData;
end
function GetDiscordName(user)
local discordId = nil
local nameData = nil;
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break
end
end
if discordId then
local endpoint = ("users/%s"):format(discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
if data ~= nil then
-- It is valid data
--print("The data for User " .. GetPlayerName(user) .. " is: ");
--print(data.avatar);
if data.discriminator == 0 or data.discriminator == "0" then return data.username end
nameData = data.username .. "#" .. data.discriminator;
--print("---")
end
else
print("[Badger_Perms] ERROR: Code 200 was not reached. DETAILS: " .. error_codes_defined[member.code])
end
end
return nameData;
end
function GetGuildIcon(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId, {})
if guild.code == 200 then
local data = json.decode(guild.data)
if (data.icon:sub(1, 1) and data.icon:sub(2, 2) == "_") then
-- It's a gif
return 'https://cdn.discordapp.com/icons/' .. Config.Guild_ID .. "/" .. data.icon .. ".gif";
else
-- Image
return 'https://cdn.discordapp.com/icons/' .. Config.Guild_ID .. "/" .. data.icon .. ".png";
end
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetGuildSplash(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId, {})
if guild.code == 200 then
local data = json.decode(guild.data)
-- Image
return 'https://cdn.discordapp.com/splashes/' .. Config.Guild_ID .. "/" .. data.icon .. ".png";
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetGuildName(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId, {})
if guild.code == 200 then
local data = json.decode(guild.data)
-- Image
return data.name;
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetGuildDescription(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId, {})
if guild.code == 200 then
local data = json.decode(guild.data)
-- Image
return data.description;
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetGuildMemberCount(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId.."?with_counts=true", {})
if guild.code == 200 then
local data = json.decode(guild.data)
-- Image
return data.approximate_member_count;
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetGuildOnlineMemberCount(guild --[[optional]])
local guildId = GetGuildId(guild)
local guild = DiscordRequest("GET", "guilds/"..guildId.."?with_counts=true", {})
if guild.code == 200 then
local data = json.decode(guild.data)
return data.approximate_presence_count;
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
end
return nil;
end
function GetDiscordAvatar(user)
local discordId = nil
local imgURL = nil;
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break
end
end
if discordId then
if Caches.Avatars[discordId] == nil then
local endpoint = ("users/%s"):format(discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
if data ~= nil and data.avatar ~= nil then
-- It is valid data
--print("The data for User " .. GetPlayerName(user) .. " is: ");
--print(data.avatar);
if (data.avatar:sub(1, 1) and data.avatar:sub(2, 2) == "_") then
--print("IMG URL: " .. "https://cdn.discordapp.com/avatars/" .. discordId .. "/" .. data.avatar .. ".gif")
imgURL = "https://cdn.discordapp.com/avatars/" .. discordId .. "/" .. data.avatar .. ".gif";
else
--print("IMG URL: " .. "https://cdn.discordapp.com/avatars/" .. discordId .. "/" .. data.avatar .. ".png")
imgURL = "https://cdn.discordapp.com/avatars/" .. discordId .. "/" .. data.avatar .. ".png"
end
--print("---")
end
else
print("[Badger_Perms] ERROR: Code 200 was not reached. DETAILS: " .. error_codes_defined[member.code])
end
Caches.Avatars[discordId] = imgURL;
else
imgURL = Caches.Avatars[discordId];
end
else
print("[Badger_Perms] ERROR: Discord ID was not found...")
end
return imgURL;
end
Caches = {
Avatars = {},
RoleList = {}
}
function ResetCaches()
Caches = {
Avatars = {},
RoleList = {},
};
end
function GetGuildRoleList(guild --[[optional]])
local guildId = GetGuildId(guild)
if (Caches.RoleList[guildId] == nil) then
local guild = DiscordRequest("GET", "guilds/"..guildId, {})
if guild.code == 200 then
local data = json.decode(guild.data)
-- Image
local roles = data.roles;
local roleList = {};
for i = 1, #roles do
roleList[roles[i].name] = roles[i].id;
end
Caches.RoleList[guildId] = roleList;
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data or guild.code))
Caches.RoleList[guildId] = nil;
end
end
return Caches.RoleList[guildId];
end
local recent_role_cache = {}
function ClearCache(discordId)
if (discordId ~= nil) then
recent_role_cache[discordId] = {};
end
end
function GetDiscordRoles(user, guild --[[optional]])
local discordId = nil
local guildId = GetGuildId(guild)
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break;
end
end
if discordId then
if Config.CacheDiscordRoles and recent_role_cache[discordId] and recent_role_cache[discordId][guildId] then
return recent_role_cache[discordId][guildId]
end
local endpoint = ("guilds/%s/members/%s"):format(guildId, discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
local roles = data.roles
local found = true
if Config.CacheDiscordRoles then
recent_role_cache[discordId] = recent_role_cache[discordId] or {}
recent_role_cache[discordId][guildId] = roles
Citizen.SetTimeout(((Config.CacheDiscordRolesTime or 60)*1000), function() recent_role_cache[discordId][guildId] = nil end)
end
return roles
else
print("[Badger_Perms] ERROR: Code 200 was not reached... Returning false. [Member Data NOT FOUND] DETAILS: " .. error_codes_defined[member.code])
return false
end
else
print("[Badger_Perms] ERROR: Discord was not connected to user's Fivem account...")
return false
end
return false
end
function GetDiscordNickname(user, guild --[[optional]])
local discordId = nil
local guildId = GetGuildId(guild)
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
break
end
end
if discordId then
local endpoint = ("guilds/%s/members/%s"):format(guildId, discordId)
local member = DiscordRequest("GET", endpoint, {})
if member.code == 200 then
local data = json.decode(member.data)
local nickname = data.nick
return nickname;
else
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
return nil;
end
else
print("[Badger_Perms] ERROR: Discord was not connected to user's Fivem account...")
return nil;
end
return nil;
end
function SetNickname(user, nickname, reason)
local discordId = nil
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, 'discord:') then
discordId = string.gsub(id, 'discord:', '')
break
end
end
if discordId then
local name = nickname or ""
local endpoint = ("guilds/%s/members/%s"):format(Config.Guild_ID, discordId)
local member = DiscordRequest("PATCH", endpoint, json.encode({nick = tostring(name)}), reason)
if member.code ~= 200 then
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
end
end
end
function AddRole(user, roleId, reason)
local discordId = nil
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, 'discord:') then
discordId = string.gsub(id, 'discord:', '')
break
end
end
if discordId then
local roles = GetDiscordRoles(user) or {}
local endpoint = ("guilds/%s/members/%s"):format(Config.Guild_ID, discordId)
table.insert(roles, roleId)
local member = DiscordRequest("PATCH", endpoint, json.encode({roles = roles}), reason)
if member.code ~= 200 then
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
end
end
end
function RemoveRole(user, roleId, reason)
local discordId = nil
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, 'discord:') then
discordId = string.gsub(id, 'discord:', '')
break
end
end
if discordId then
local roles = GetDiscordRoles(user) or {}
local endpoint = ("guilds/%s/members/%s"):format(Config.Guild_ID, discordId)
for k, v in pairs(roles) do
if v == roleId then
roles[k] = nil
end
end
local member = DiscordRequest("PATCH", endpoint, json.encode({roles = roles}), reason)
if member.code ~= 200 then
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
end
end
end
function SetRoles(user, roleList, reason)
local discordId = nil
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, 'discord:') then
discordId = string.gsub(id, 'discord:', '')
break
end
end
if discordId then
local endpoint = ("guilds/%s/members/%s"):format(Config.Guild_ID, discordId)
local member = DiscordRequest("PATCH", endpoint, json.encode({roles = roleList}), reason)
if member.code ~= 200 then
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
end
end
end
function ChangeDiscordVoice(user, voice, reason)
local discordId = nil
for _, id in ipairs(GetPlayerIdentifiers(user)) do
if string.match(id, "discord:") then
discordId = string.gsub(id, "discord:", "")
end
end
if discordId then
local endpoint = ("guilds/%s/members/%s"):format(Config.Guild_ID, discordId)
local member = DiscordRequest("PATCH", endpoint, json.encode({channel_id = voice}), reason)
if member.code ~= 200 then
print("[Badger_Perms] ERROR: Code 200 was not reached. Error Code: " .. error_codes_defined[member.code])
end
end
end
Citizen.CreateThread(function()
local mguild = DiscordRequest("GET", "guilds/"..Config.Guild_ID, {})
if mguild.code == 200 then
local data = json.decode(mguild.data)
print("[Badger_Perms] Successful connection to Guild : "..data.name.." ("..data.id..")")
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(mguild.data and json.decode(mguild.data) or mguild.code))
end
if (Config.Multiguild) then
for _,guildID in pairs(Config.Guilds) do
local guild = DiscordRequest("GET", "guilds/"..guildID, {})
if guild.code == 200 then
local data = json.decode(guild.data)
print("[Badger_Perms] Successful connection to Guild : "..data.name.." ("..data.id..")")
else
print("[Badger_Perms] An error occured, please check your config and ensure everything is correct. Error: "..(guild.data and json.decode(guild.data) or guild.code))
end
end
end
end)