This repository has been archived by the owner on May 15, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 67
/
roblox.py
2847 lines (2140 loc) · 133 KB
/
roblox.py
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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from ..structures.Bloxlink import Bloxlink # pylint: disable=no-name-in-module, import-error
from ..structures.Card import Card # pylint: disable=no-name-in-module, import-error
from ..exceptions import (BadUsage, RobloxAPIError, Error, CancelCommand, UserNotVerified,# pylint: disable=no-name-in-module, import-error
RobloxNotFound, PermissionError, BloxlinkBypass, RobloxDown, Blacklisted)
from typing import Tuple
import discord
from datetime import datetime
from config import REACTIONS # pylint: disable=import-error, no-name-in-module
from ..constants import (BLOXLINK_STAFF, RELEASE, DEFAULTS,SERVER_INVITE, GREEN_COLOR, # pylint: disable=import-error, no-name-in-module
RED_COLOR, VERIFY_URL, IGNORED_SERVERS, CLUSTER_ID, ORANGE_COLOR) # pylint: disable=import-error, no-name-in-module
import json
import re
import asyncio
import dateutil.parser as parser
import math
import traceback
import uuid
import async_timeout
nickname_template_regex = re.compile(r"\{(.*?)\}")
any_group_nickname = re.compile(r"\{group-rank-(.*?)\}")
bracket_search = re.compile(r"\[(.*)\]")
roblox_group_regex = re.compile(r"roblox.com/groups/(\d+)/")
fetch, post_event = Bloxlink.get_module("utils", attrs=["fetch", "post_event"])
has_premium = Bloxlink.get_module("premium", attrs=["has_premium"])
cache_set, cache_get, cache_pop, get_guild_value, get_db_value, get_user_value, set_db_value, set_user_value = Bloxlink.get_module("cache", attrs=["set", "get", "pop", "get_guild_value", "get_db_value", "get_user_value", "set_db_value", "set_user_value"])
check_restrictions = Bloxlink.get_module("blacklist", attrs=["check_restrictions"])
has_magic_role = Bloxlink.get_module("extras", attrs=["has_magic_role"])
API_URL = "https://api.roblox.com"
BASE_URL = "https://www.roblox.com"
GROUP_API = "https://groups.roblox.com"
THUMBNAIL_API = "https://thumbnails.roblox.com"
@Bloxlink.module
class Roblox(Bloxlink.Module):
def __init__(self):
self.pending_verifications = {}
self.pending_tasks = {}
async def __setup__(self):
pubsub = self.redis.pubsub()
await pubsub.subscribe(f"ACCOUNT_CONFIRM:{CLUSTER_ID}")
while True:
try:
message = await pubsub.get_message(ignore_subscribe_messages=True)
if message:
self.loop.create_task(self.account_confirm_message(message))
except self.redis.exceptions.ConnectionError:
while True:
try:
await self.redis.ping()
except self.redis.exceptions.ConnectionError:
await asyncio.sleep(10)
else:
await pubsub.subscribe(f"ACCOUNT_CONFIRM:{CLUSTER_ID}")
break
async def account_confirm_message(self, message):
message = json.loads(str(message["data"], "utf-8"))
data = message["data"]
nonce = message["nonce"]
task = self.pending_tasks.get(nonce)
if not task:
return
if not task.done():
task.set_result(bool(data.get("confirmed")))
else:
self.pending_tasks.pop(nonce, None)
async def confirm_account(self, guild_id, roblox_id):
future = self.loop.create_future()
nonce = str(uuid.uuid4())
self.pending_tasks[nonce] = future
await self.redis.set(f"account_confirm:{guild_id}:{roblox_id}", json.dumps([nonce, CLUSTER_ID]), ex=3600)
try:
async with async_timeout.timeout(1000):
await future
except asyncio.TimeoutError:
pass
result = self.pending_tasks[nonce].result()
self.pending_tasks.pop(nonce, None)
return result
async def send_account_confirmation(self, user, roblox_account, guild, response, ephemeral=False):
if roblox_account and not "premium" in (await has_premium(guild=guild)).features:
roblox_accounts = await get_user_value(user, "robloxAccounts") or {"confirms": {}}
user_confirms = roblox_accounts.get("confirms", {})
if user_confirms.get(str(roblox_account.id)) in (True, str(guild.id)): # FIXME: old confirms, need to pop from database
user_confirms.pop(str(roblox_account.id), None)
roblox_accounts["confirms"] = user_confirms
await set_user_value(user, robloxAccounts=roblox_accounts)
if user_confirms.get(str(guild.id)) == str(roblox_account.id):
return
try:
view = discord.ui.View()
embed = discord.Embed(
title="Confirm Account",
description=f"Are you sure you want to use Roblox account **{roblox_account.username}** in this server?"
)
embed.colour = ORANGE_COLOR
view.add_item(
item=discord.ui.Button(style=discord.ButtonStyle.link, label="Confirm Account", url=f"https://blox.link/confirm/{guild.id}/{roblox_account.id}")
)
view.add_item(
item=discord.ui.Button(style=discord.ButtonStyle.link, label="Deny Account", url=f"https://blox.link/confirm/{guild.id}/{roblox_account.id}")
)
confirmation_message = await response.send(embed=embed, view=view, hidden=ephemeral)
confirmed = await self.confirm_account(guild.id, roblox_account.id)
if not confirmed:
raise CancelCommand()
embed.colour = GREEN_COLOR
embed.description = "Thanks for confirming the account! Confirmation helps us secure verifications."
embed.title = "Confirmed Account"
await confirmation_message.edit(embed=embed)
user_confirms[str(guild.id)] = str(roblox_account.id)
roblox_accounts["confirms"] = user_confirms
await set_user_value(user, robloxAccounts=roblox_accounts)
except discord.errors.Forbidden:
raise CancelCommand()
async def mask_unverified(self, guild, member): # only used for non-premium servers to mask a user as unverified so they can confirm prompt
if not "premium" in (await has_premium(guild=guild)).features:
options = await get_guild_value(guild,
["unverifiedRoleEnabled", DEFAULTS.get("unverifiedRoleEnabled")],
"unverifiedRole",)
unverify_role_enabled = options.get("unverifiedRoleEnabled")
unverified_role_name = options.get("unverifiedRoleName") or DEFAULTS.get("unverifiedRoleName")
unverified_role_id = int(options.get("unverifiedRole")) if options.get("unverifiedRole") else None
unverified_role = None
if unverify_role_enabled:
if unverified_role_id:
unverified_role = discord.utils.find(lambda r: (r.id == unverified_role_id) and not r.managed, guild.roles)
if not unverified_role:
unverified_role = discord.utils.find(lambda r: (r.name == unverified_role_name.strip()) and not r.managed, guild.roles)
if not unverified_role:
try:
unverified_role = await guild.create_role(name=unverified_role_name, reason="Creating missing Unverified role")
except discord.errors.Forbidden:
raise PermissionError("I was unable to create the Unverified Role. Please "
"ensure I have the `Manage Roles` permission.")
except discord.errors.HTTPException:
raise Error("Unable to create role: this server has reached the max amount of roles!")
try:
await member.add_roles(unverified_role)
except discord.errors.Forbidden:
raise PermissionError("I was unable to give you the Unverified role.")
except discord.errors.NotFound:
raise CancelCommand()
@staticmethod
async def get_roblox_id(username) -> Tuple[str, str]:
username_lower = username.lower()
roblox_cached_data = await cache_get(f"usernames_to_ids:{username_lower}")
if roblox_cached_data:
return roblox_cached_data
json_data, response = await fetch(f"{API_URL}/users/get-by-username/?username={username}", json=True, raise_on_failure=True)
if json_data.get("success") is False:
raise RobloxNotFound
correct_username, roblox_id = json_data.get("Username"), str(json_data.get("Id"))
data = (roblox_id, correct_username)
if correct_username:
await cache_set(f"usernames_to_ids:{username_lower}", data)
return data
@staticmethod
async def get_roblox_username(roblox_id) -> Tuple[str, str]:
roblox_user = await cache_get(f"roblox_users:{roblox_id}")
if roblox_user and roblox_user.verified:
return roblox_user.id, roblox_user.username
json_data, response = await fetch(f"{API_URL}/users/{roblox_id}", json=True, raise_on_failure=True)
if json_data.get("success") is False:
raise RobloxNotFound
correct_username, roblox_id = json_data.get("Username"), str(json_data.get("Id"))
data = (roblox_id, correct_username)
return data
@staticmethod
async def validate_code(roblox_id, code):
if RELEASE == "LOCAL":
return True
try:
html_text, _ = await fetch(f"https://www.roblox.com/users/{roblox_id}/profile", raise_on_failure=True)
except RobloxNotFound:
raise Error("You cannot link as a banned user. Please try again with another user.")
return code in html_text
async def parse_accounts(self, accounts, reverse_search=False):
parsed_accounts = {}
for account in accounts:
roblox_user = RobloxUser(roblox_id=account)
await roblox_user.sync()
if reverse_search:
discord_ids = await get_db_value("roblox_accounts", account, "discordIDs") or []
discord_accounts = []
for discord_id in discord_ids:
try:
user = await Bloxlink.fetch_user(int(discord_id))
except discord.errors.NotFound:
pass
else:
discord_accounts.append(user)
parsed_accounts[roblox_user.username] = (roblox_user, discord_accounts)
else:
parsed_accounts[roblox_user.username] = roblox_user
return parsed_accounts
@staticmethod
async def count_binds(guild):
all_binds = await get_guild_value(guild, ["roleBinds", {}], ["groupIDs", {}])
role_binds = all_binds["roleBinds"]
group_ids = all_binds["groupIDs"]
bind_count = 0
for bind_category, binds in role_binds.items():
for bind_data in binds.values():
if bind_data:
if bind_category == "groups":
bind_count += len(bind_data.get("binds", {})) + len(bind_data.get("ranges", {}))
else:
bind_count += 1
bind_count += len(group_ids)
return bind_count
async def extract_accounts(self, user, resolve_to_users=True, reverse_search=False):
roblox_ids = {}
options = await get_user_value(user, "robloxID", ["robloxAccounts", {}])
primary_account = options.get("robloxID")
if primary_account:
roblox_ids[primary_account] = True
for roblox_id in options.get("robloxAccounts", {}).get("accounts", []):
roblox_ids[roblox_id] = True
if reverse_search:
for roblox_id in roblox_ids.keys():
discord_ids = await get_db_value("roblox_accounts", roblox_id, "discordIDs") or []
discord_accounts = []
if resolve_to_users:
for discord_id in discord_ids:
try:
user = await Bloxlink.fetch_user(int(discord_id))
except discord.errors.NotFound:
pass
else:
discord_accounts.append(user)
else:
discord_accounts = discord_ids
roblox_ids[roblox_id] = discord_accounts
return roblox_ids
else:
return list(roblox_ids.keys())
async def verify_member(self, user, roblox, guild=None, primary_account=False, allow_reverify=True):
user_id = str(user.id)
guild = guild or getattr(user, "guild", None)
guild_id = guild and str(guild.id)
set_options = {}
if isinstance(roblox, RobloxUser):
roblox_id = str(roblox.id)
else:
roblox_id = str(roblox)
roblox_accounts = await get_user_value(user, "robloxAccounts") or {}
roblox_list = roblox_accounts.get("accounts", [])
if guild:
guild_list = roblox_accounts.get("guilds", {})
guild_find = guild_list.get(guild_id)
if guild_find and not allow_reverify and guild_find != roblox:
raise Error("You already selected your account for this server! `allowReVerify` must be enabled for you to change your account.")
guild_list[guild_id] = roblox_id
roblox_accounts["guilds"] = guild_list
if not roblox_id in roblox_list:
roblox_list.append(roblox_id)
roblox_accounts["accounts"] = roblox_list
discord_ids = await get_db_value("roblox_accounts", roblox_id, "discordIDs") or []
if user_id not in discord_ids:
discord_ids.append(user_id)
await set_db_value("roblox_accounts", roblox_id, discordIDs=discord_ids)
if primary_account:
set_options["robloxID"] = roblox_id
set_options["robloxAccounts"] = roblox_accounts
await set_user_value(user, **set_options)
await cache_pop(f"discord_profiles:{user_id}")
async def unverify_member(self, user, roblox):
user_id = str(user.id)
success = False
set_options = {}
if isinstance(roblox, RobloxUser):
roblox_id = str(roblox.id)
else:
roblox_id = str(roblox)
await check_restrictions("users", user.id) or await check_restrictions("robloxAccounts", roblox_id)
options = await get_user_value(user, ["robloxAccounts", {}], "robloxID")
roblox_accounts = options.get("robloxAccounts", {})
roblox_list = roblox_accounts.get("accounts", [])
guilds = roblox_accounts.get("guilds", {})
discord_ids = await get_db_value("roblox_accounts", roblox_id, "discordIDs") or []
if roblox_id in roblox_list:
roblox_list.remove(roblox_id)
roblox_accounts["accounts"] = roblox_list
success = True
for i,v in dict(guilds).items():
if v == roblox_id:
try:
guild = await Bloxlink.fetch_guild(int(i))
except (discord.errors.Forbidden, discord.errors.HTTPException):
pass
else:
try:
member = await guild.fetch_member(user.id)
except (discord.errors.Forbidden, discord.errors.NotFound):
pass
else:
for role in member.roles:
if role != guild.default_role and role.name != "Muted":
try:
await member.remove_roles(role, reason="Unlinked")
except discord.errors.Forbidden:
pass
guilds.pop(i, None)
success = True
if options.get("robloxID") == roblox_id:
set_options["robloxID"] = None
roblox_accounts["guilds"] = guilds
set_options["robloxAccounts"] = roblox_accounts
if user_id in discord_ids:
discord_ids.remove(user_id)
if not discord_ids:
#await self.r.table("robloxAccounts").get(roblox_id).delete().run()
pass
else:
await set_db_value("roblox_accounts", roblox_id, discordIDs=discord_ids)
await set_user_value(user, **set_options)
await cache_pop(f"discord_profiles:{user_id}")
return success
async def get_clan_tag(self, user, guild, response, dm=False):
clan_tags = await get_user_value(user, "clanTags") or {}
def get_from_db():
return clan_tags.get(str(guild.id))
if not response:
return get_from_db()
# TODO: make a modal
# clan_tag = (await response.prompt([{
# "prompt": "Please provide text for your Clan Tag. This will be inserted into "
# "your nickname.\n**Please keep your clan tag under 10 characters**, "
# "or it may not properly show.\nIf you want to skip this, then say `skip`.",
# "name": "clan_tag",
# "max": 32
# }], dm=dm))["clan_tag"]
# if clan_tag.lower() == "skip":
# return get_from_db()
# clan_tags[str(guild.id)] = clan_tag
# user_data["clanTags"] = clan_tags
# await self.r.db("bloxlink").table("users").insert(user_data, conflict="update").run()
clan_tag = get_from_db() # FIXME
return clan_tag
async def save_binds_explanations(self, bind_explanations):
nonce = str(uuid.uuid4())
await self.redis.set(f"binds:{nonce}", json.dumps(bind_explanations), ex=3600)
return nonce
async def get_binds_explanation_button(self, bind_explanations):
if bind_explanations is not None:
binds_token = await self.save_binds_explanations(bind_explanations)
bind_explanation_button = discord.ui.Button(style=discord.ButtonStyle.link,
label="Expecting different roles?",
url=f"https://{'bloxlink.dev' if RELEASE in ('LOCAL', 'CANARY') else 'blox.link'}/binds/{binds_token}")
return bind_explanation_button
async def format_update_embed(self, roblox_user, user, *, guild, added, removed, errors, warnings, nickname, author=None, from_interaction=True, bind_explanations=None):
author = author or user
welcome_message = await get_guild_value(guild, ["welcomeMessage", DEFAULTS.get("welcomeMessage")])
welcome_message = await self.get_nickname(user, welcome_message, roblox_user=roblox_user, is_nickname=False)
embed = None
card = None
view = discord.ui.View()
bind_explanation_button = await self.get_binds_explanation_button(bind_explanations)
if not (added or removed or errors or nickname):
embed = discord.Embed(description="This user is all up-to-date; no changes were made. If this message isn't what you expected, then please contact this server's admins as they did not set up the bot or role permissions correctly.")
if bind_explanation_button:
view.add_item(item=bind_explanation_button)
else:
high_traffic_server = await get_guild_value(guild, "highTrafficServer")
if not high_traffic_server:
author_accounts = await self.get_accounts(author)
card = Card(user, author, author_accounts, roblox_user, "verify", guild, extra_components=[bind_explanation_button] if bind_explanations is not None else [], extra_data={"added": added, "removed": removed, "nickname": nickname, "errors": errors, "warnings": warnings}, from_interaction=from_interaction)
await card()
else:
welcome_message = "You were successfully verified!"
if bind_explanations is not None:
view.add_item(item=bind_explanation_button)
# view = discord.ui.View()
# view.add_item(item=discord.ui.Button(style=discord.ButtonStyle.link, label="Add/Change Account", url=VERIFY_URL, emoji="🔗"))
# view.add_item(item=discord.ui.Button(style=discord.ButtonStyle.link, label="Remove Account", emoji="🧑🔧", url=ACCOUNT_SETTINGS_URL))
return welcome_message, card, embed, view
async def get_nickname(self, user, template=None, group=None, *, guild=None, skip_roblox_check=False, response=None, is_nickname=True, roblox_user=None, dm=False):
template = template or ""
if template == "{disable-nicknaming}":
return
guild = guild or user.guild
roblox_user = roblox_user or (not skip_roblox_check and (await self.get_user(user=user, everything=True))[0])
if isinstance(roblox_user, tuple):
roblox_user = roblox_user[0]
if roblox_user:
if not roblox_user.complete:
await roblox_user.sync(everything=True)
if not group:
groups = list((await get_guild_value(guild, ["groupIDs", {}])).keys())
group_id = groups and groups[0]
if group_id:
group = roblox_user.groups.get(group_id)
group_role = group and group.user_rank_name or "Guest"
if await get_guild_value(guild, ["shorterNicknames", DEFAULTS.get("shorterNicknames")]):
if group_role != "Guest":
brackets_match = bracket_search.search(group_role)
if brackets_match:
group_role = f"[{brackets_match.group(1)}]"
template = template or DEFAULTS.get("nicknameTemplate") or ""
if template == "{disable-nicknaming}":
return
for group_id in any_group_nickname.findall(template):
group = roblox_user.groups.get(group_id)
group_role_from_group = group and group.user_rank_name or "Guest"
if await get_guild_value(guild, ["shorterNicknames", DEFAULTS.get("shorterNicknames")]):
if group_role_from_group != "Guest":
brackets_match = bracket_search.search(group_role_from_group)
if brackets_match:
group_role_from_group = f"[{brackets_match.group(1)}]"
template = template.replace("{group-rank-"+group_id+"}", group_role_from_group)
if "smart-name" in template:
if roblox_user.display_name != roblox_user.username:
smart_name = f"{roblox_user.display_name} (@{roblox_user.username})"
if len(smart_name) > 32:
smart_name = roblox_user.username
else:
smart_name = roblox_user.username
else:
smart_name = ""
template = template.replace(
"roblox-name", roblox_user.username
).replace(
"display-name", roblox_user.display_name,
).replace(
"smart-name", smart_name,
).replace(
"roblox-id", str(roblox_user.id)
).replace(
"roblox-age", str(roblox_user.age)
).replace(
"roblox-join-date", roblox_user.join_date
).replace(
"group-rank", group_role
)
else:
if not template:
template = await get_guild_value(guild, ["unverifiedNickname", DEFAULTS.get("unverifiedNickname")]) or ""
if template == "{disable-nicknaming}":
return
template = template.replace(
"discord-name", user.name
).replace(
"discord-nick", user.display_name
).replace(
"discord-mention", user.mention
).replace(
"discord-id", str(user.id)
).replace(
"server-name", guild.name
).replace(
"prefix", "/"
).replace(
"group-url", group.url if group else ""
).replace(
"group-name", group.name if group else ""
)
for outer_nick in nickname_template_regex.findall(template):
nick_data = outer_nick.split(":")
nick_fn = None
nick_value = None
if len(nick_data) > 1:
nick_fn = nick_data[0]
nick_value = nick_data[1]
else:
nick_value = nick_data[0]
# nick_fn = capA
# nick_value = roblox-name
if nick_fn:
if nick_fn in ("allC", "allL"):
if nick_fn == "allC":
nick_value = nick_value.upper()
elif nick_fn == "allL":
nick_value = nick_value.lower()
template = template.replace("{{{0}}}".format(outer_nick), nick_value)
else:
template = template.replace("{{{0}}}".format(outer_nick), outer_nick) # remove {} only
else:
template = template.replace("{{{0}}}".format(outer_nick), nick_value)
# clan tags are done at the end bc we may need to shorten them, and brackets are removed at the end
clan_tag = "clan-tag" in template and (await self.get_clan_tag(user=user, guild=guild, response=response, dm=dm) or "N/A")
if is_nickname:
if clan_tag:
characters_left = 32 - len(template) + 8
clan_tag = clan_tag[:characters_left]
template = template.replace("clan-tag", clan_tag)
return template[:32]
else:
if clan_tag:
template = template.replace("clan-tag", clan_tag)
return template
async def get_binds(self, guild):
role_binds = await get_guild_value(guild, "roleBinds") or {}
group_ids = await get_guild_value(guild, "groupIDs") or {}
role_binds["groups"] = role_binds.get("groups", {})
role_binds["assets"] = role_binds.get("assets", {})
role_binds["badges"] = role_binds.get("badges", {})
role_binds["gamePasses"] = role_binds.get("gamePasses", {})
return role_binds, group_ids
async def guild_obligations(self, member, guild, join=None, cache=True, dm=False, event=False, response=None, exceptions=None, roles=True, nickname=True, roblox_user=None):
if member.bot:
raise CancelCommand()
if guild.id in IGNORED_SERVERS:
raise CancelCommand()
if self.pending_verifications.get(member.id):
raise CancelCommand("You are already queued for verification. This process can take a while depending on the size of the server due to Discord rate-limits.")
self.pending_verifications[member.id] = True
try:
roblox_user = None
accounts = []
donator_profile = None
unverified = False
exceptions = exceptions or ()
added, removed, errored, warnings, chosen_nickname = [], [], [], [], None
card = None
embed = None
bind_explanations = {"success": [], "failure": []}
if RELEASE == "PRO":
donator_profile = await has_premium(guild=guild)
if "pro" not in donator_profile.features:
raise CancelCommand
try:
roblox_user, accounts, _ = await self.get_user(user=member, everything=True, cache=cache)
except UserNotVerified:
unverified = True
except RobloxAPIError as e:
if "RobloxAPIError" in exceptions:
raise RobloxAPIError from e
except RobloxDown:
if "RobloxDown" in exceptions:
raise RobloxDown
else:
raise CancelCommand
if not roblox_user:
unverified = True
async def post_log(channel_data, color):
if event and channel_data:
if not unverified:
if channel_data.get("verified") and channel_data["verified"].get("channel"):
channel_id = int(channel_data["verified"]["channel"])
channel = discord.utils.find(lambda c: c.id == channel_id, guild.text_channels)
if channel:
join_channel_message = channel_data["verified"]["message"]
join_message_parsed = (await self.get_nickname(member, join_channel_message, roblox_user=roblox_user, dm=dm, is_nickname=False))[:1500]
includes = channel_data["verified"]["includes"]
embed = discord.Embed(description=join_message_parsed)
content = None
view = None
use_embed = False
if includes:
embed_description_buffer = []
if includes.get("robloxAvatar"):
use_embed = True
embed.set_thumbnail(url=roblox_user.avatar)
if includes.get("robloxUsername"):
use_embed = True
embed_description_buffer.append(f"**Roblox username:** {roblox_user.username}")
if includes.get("robloxAge"):
use_embed = True
embed_description_buffer.append(f"**Roblox account created:** {roblox_user.full_join_string}")
if use_embed:
embed.set_author(name=str(member), icon_url=member.avatar.url if member.avatar else None, url=roblox_user.profile_link)
embed.set_footer(text="Disclaimer: the message above was set by the Server Admins. The ONLY way to verify with Bloxlink "
"is through https://blox.link and NO other link.")
embed.colour = color
view = discord.ui.View()
view.add_item(item=discord.ui.Button(style=discord.ButtonStyle.link, label="Visit Profile", url=roblox_user.profile_link, emoji="👥"))
if embed_description_buffer:
embed_description_buffer = "\n".join(embed_description_buffer)
embed.description = f"{embed.description}\n\n{embed_description_buffer}"
if not use_embed:
embed = None
content = f"{join_message_parsed}\n\n**Disclaimer:** the message above was set by the Server Admins. The ONLY way to verify with Bloxlink " \
"is through <https://blox.link> and NO other link."
if includes.get("ping"):
content = f"{member.mention} {content or ''}"
try:
await channel.send(content=content, embed=embed, view=view)
except (discord.errors.NotFound, discord.errors.Forbidden):
pass
else:
if channel_data.get("unverified") and channel_data["unverified"].get("channel"):
channel_id = int(channel_data["unverified"]["channel"])
channel = discord.utils.find(lambda c: c.id == channel_id, guild.text_channels)
if channel:
join_channel_message = channel_data["unverified"]["message"]
join_message_parsed = (await self.get_nickname(member, join_channel_message, skip_roblox_check=True, dm=dm, is_nickname=False))[:2000]
includes = channel_data["unverified"].get("includes") or {}
format_embed = channel_data["unverified"].get("embed")
embed = None
content = None
if format_embed:
embed = discord.Embed(description=join_message_parsed)
embed.set_author(name=str(member), icon_url=member.avatar.url if member.avatar else None)
embed.set_footer(text="Disclaimer: the message above was set by the Server Admins. The ONLY way to verify with Bloxlink "
"is through https://blox.link and NO other link.")
embed.colour = color
else:
content = f"{join_message_parsed}\n\n**Disclaimer:** the message above was set by the Server Admins. The ONLY way to verify with Bloxlink " \
"is through <https://blox.link> and NO other link."
if includes.get("ping"):
content = f"{member.mention} {content or ''}"
try:
await channel.send(content=content, embed=embed)
except (discord.errors.NotFound, discord.errors.Forbidden):
pass
if join is not False:
options = await get_guild_value(guild, ["verifiedDM", DEFAULTS.get("welcomeMessage")], ["unverifiedDM", DEFAULTS.get("unverifiedDM")], "ageLimit", ["disallowAlts", DEFAULTS.get("disallowAlts")], ["disallowBanEvaders", DEFAULTS.get("disallowBanEvaders")], "groupLock", "joinChannel", "highTrafficServer")
verified_dm = options.get("verifiedDM")
join_channel = options.get("joinChannel")
unverified_dm = options.get("unverifiedDM")
age_limit = options.get("ageLimit")
disallow_alts = options.get("disallowAlts")
disallow_ban_evaders = options.get("disallowBanEvaders")
high_traffic_server = options.get("highTrafficServer")
if high_traffic_server:
dm = False
try:
age_limit = int(age_limit) #FIXME
except TypeError:
age_limit = None
if disallow_alts or disallow_ban_evaders:
if not donator_profile:
donator_profile = await has_premium(guild=guild)
if "premium" in donator_profile.features:
accounts = set(accounts)
if roblox_user: #FIXME: temp until primary accounts are saved to the accounts array
accounts.add(roblox_user.id)
if accounts and (disallow_alts or disallow_ban_evaders):
for roblox_id in accounts:
discord_ids = await get_db_value("roblox_accounts", roblox_id, "discordIDs") or []
for discord_id in discord_ids:
discord_id = int(discord_id)
if discord_id != member.id:
if disallow_alts:
# check the server
try:
user_find = await guild.fetch_member(discord_id)
except discord.errors.NotFound:
pass
else:
if dm:
try:
await member.send(f"This server ({guild.name}) forbids the use of alterantive accounts, so your old account has been removed from the server.")
except discord.errors.Forbidden:
pass
try:
await user_find.kick(reason=f"disallowAlts is enabled - alt of {member} ({member.id})")
except discord.errors.Forbidden:
pass
else:
await post_event(guild, "moderation", f"{user_find.mention} is an alt of {member.mention} and has been `kicked`.", RED_COLOR)
raise CancelCommand
if disallow_ban_evaders:
# check the bans
try:
ban_entry = await guild.fetch_ban(discord.Object(discord_id))
except (discord.errors.NotFound, discord.errors.Forbidden):
pass
else:
action = disallow_ban_evaders == "kick" and "kick" or "ban"
action_participle = action == "kick" and "kicked" or "banned"
if dm:
try:
await member.send(f"This server ({guild.name}) forbids ban-evaders, and as you have a banned account in the server, you have been {action_participle}.")
except discord.errors.Forbidden:
pass
try:
await ((getattr(guild, action))(member, reason=f"disallowBanEvaders is enabled - alt of {ban_entry.user} ({ban_entry.user.id})"))
except (discord.errors.Forbidden, discord.errors.HTTPException):
pass
else:
await post_event(guild, "moderation", f"{member.mention} is an alt of {ban_entry.user.mention} and has been `{action_participle}`.", RED_COLOR)
raise CancelCommand
return added, removed, chosen_nickname, errored, warnings, roblox_user, None
try:
added, removed, chosen_nickname, errored, warnings, _, bind_explanations = await self.update_member(
member,
guild = guild,
roles = roles,
nickname = nickname,
roblox_user = roblox_user,
cache = cache,
dm = dm,
response = response)
except discord.errors.NotFound as e:
if "NotFound" in exceptions:
raise e from None
except RobloxAPIError as e:
if "RobloxAPIError" in exceptions:
raise e from None
except Error as e:
if "Error" in exceptions:
raise e from None
except CancelCommand as e:
if "CancelCommand" in exceptions:
raise e from None
except RobloxDown as e:
if "RobloxDown" in exceptions:
raise e from None
else:
raise CancelCommand
except Blacklisted as e:
if "Blacklisted" in exceptions:
raise e from None
except BloxlinkBypass as e:
if "BloxlinkBypass" in exceptions:
raise e from None
except PermissionError as e:
if "PermissionError" in exceptions:
raise e from None
except (UserNotVerified, discord.errors.HTTPException):
pass
required_groups = options.get("groupLock")
if roblox_user:
if event:
await post_event(guild, "verification", f"{member.mention} has **verified** as `{roblox_user.username}`.", GREEN_COLOR)
if age_limit:
if age_limit > roblox_user.age:
if dm:
try:
await member.send(f"_Bloxlink Age-Limit_\nYou were kicked from **{guild.name}** for not being at least "
f"`{age_limit}` days old on your Roblox account `{roblox_user.username}` (days={roblox_user.age}). If this is a mistake, "
f"then please join {SERVER_INVITE} and link a different account with `/verify`. "
f"Finally, use the `/switchuser` command and provide this ID to the command: `{guild.id}`")
except discord.errors.Forbidden:
pass
try:
await member.kick(reason=f"AGE-LIMIT: user age {roblox_user.age} < {age_limit}")
except discord.errors.Forbidden:
pass
else:
raise CancelCommand
return added, removed, chosen_nickname, errored, warnings, roblox_user, bind_explanations
if required_groups:
for group_id, group_data in required_groups.items():
user_group = roblox_user.groups.get(group_id)
group = user_group or await self.get_group(group_id, full_group=True)
group_lock_action = group_data.get("verifiedAction", "kick")
required_rolesets = group_data.get("roleSets")
if group_lock_action == "kick":
if user_group and required_rolesets:
default_dm = DEFAULTS.get("groupLockKickMessageRolesetsVerified")
else:
default_dm = DEFAULTS.get("groupLockKickMessageVerified")
else:
if user_group and required_rolesets:
default_dm = DEFAULTS.get("groupLockDMMessageRolesetsVerified")
else:
default_dm = DEFAULTS.get("groupLockDMMessageVerified")
dm_message_raw = group_data.get("dmMessage") or default_dm
dm_message = await self.get_nickname(member, dm_message_raw, guild=guild, is_nickname=False, group=user_group or group, roblox_user=roblox_user)
view = discord.ui.View()
if dm_message_raw and dm_message_raw != default_dm:
view.add_item(item=discord.ui.Button(label="The text above was set by the Server Admins. ONLY verify from https://blox.link.",