-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathfunctions.py
1474 lines (1292 loc) · 54.3 KB
/
functions.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
import asyncio
import os
import traceback
from datetime import datetime
from copy import deepcopy
from math import ceil
from random import choice, seed
from statistics import mean
from time import time
import cfg
import discord
import translate
import utils
from utils import log
import roman
try:
import patreon_info
except ImportError:
patreon_info = None
@utils.func_timer()
def lock_channel_request(channel, offset=0):
cfg.CURRENT_REQUESTS[channel.id] = time() + offset
# print("Locking", channel.id, cfg.CURRENT_REQUESTS)
@utils.func_timer()
def channel_is_requested(channel):
# print("Checking", channel.id, cfg.CURRENT_REQUESTS)
channel_age = datetime.utcnow().timestamp() - channel.created_at.timestamp()
if channel_age < 5:
return True
if channel.id in cfg.CURRENT_REQUESTS:
if time() - cfg.CURRENT_REQUESTS[channel.id] < 5:
return True
return False
@utils.func_timer()
def unlock_channel_request(channel):
try:
del cfg.CURRENT_REQUESTS[channel.id]
except KeyError:
pass
# print("Unlocking", channel.id, cfg.CURRENT_REQUESTS)
@utils.func_timer()
def lock_user_request(user, offset=0):
cfg.USER_REQUESTS[user.id] = time() + offset
@utils.func_timer()
def user_request_is_locked(user):
if user.id in cfg.USER_REQUESTS:
if time() - cfg.USER_REQUESTS[user.id] < 2:
return True
return False
@utils.func_timer()
def detect_abuse(user):
if user.id in cfg.USER_REQUESTS:
v = 1 if user.id not in cfg.USER_ABUSE_EVENTS else cfg.USER_ABUSE_EVENTS[user.id] + 1
cfg.USER_ABUSE_EVENTS[user.id] = v
return v
return False
@utils.func_timer()
def esc_md(text):
return discord.utils.escape_markdown(text)
@utils.func_timer()
def user_hash(user):
return esc_md(user.name) + "#" + user.discriminator
@utils.func_timer()
def check_primary_permissions(channel, me):
perms = channel.permissions_for(me)
perms_required = [
perms.manage_channels,
perms.read_messages,
perms.send_messages,
perms.move_members,
]
if channel.category:
perms = channel.category.permissions_for(me)
perms_required += [
perms.manage_channels,
perms.read_messages,
perms.send_messages,
perms.move_members,
]
return all(perms_required)
@utils.func_timer()
def set_template(guild, chid, template):
settings = utils.get_serv_settings(guild)
for p in settings["auto_channels"]:
for sid in settings["auto_channels"][p]["secondaries"]:
if sid == chid:
settings["auto_channels"][p]["template"] = template
utils.set_serv_settings(guild, settings)
return
@utils.func_timer()
async def set_default_limit(guild, c, limit):
chid = c.id
await c.edit(user_limit=limit)
settings = utils.get_serv_settings(guild)
for p in settings["auto_channels"]:
for sid in settings["auto_channels"][p]["secondaries"]:
if sid == chid:
settings["auto_channels"][p]["limit"] = limit
utils.set_serv_settings(guild, settings)
pc = guild.get_channel(int(p))
if pc.user_limit:
await pc.edit(user_limit=0)
return
@utils.func_timer()
def toggle_position(guild, chid):
settings = utils.get_serv_settings(guild)
for p in settings["auto_channels"]:
for sid in settings["auto_channels"][p]["secondaries"]:
if sid == chid:
above = True
if "above" in settings["auto_channels"][p]:
above = settings["auto_channels"][p]["above"]
settings["auto_channels"][p]["above"] = not above
utils.set_serv_settings(guild, settings)
above = not above
return "above" if above else "below"
return "error"
@utils.func_timer()
def get_channel_games(channel):
settings = utils.get_serv_settings(channel.guild)
general = ["General"] if "general" not in settings else [settings["general"]]
games = {}
for m in sorted(channel.members, key=lambda x: x.display_name.lower()):
if not m.bot:
for act in [a for a in m.activities if a.type == discord.ActivityType.playing]:
gname = act.name
if gname == "Custom Status":
continue
if gname in games:
games[gname] += 1
else:
games[gname] = 1
if not games:
return general
games_l = list((x, games[x]) for x in games) # Convert dict to 2D list
games_l.sort(key=lambda c: c[1], reverse=True) # Sort by most players
biggest_game, most_players = games_l[0]
gnames = [biggest_game]
games_l = games_l[1:] # remaining games (excluding most popular one)
for gn, gp in games_l:
if gp == most_players:
gnames.append(gn)
if len(gnames) > 2:
# More than 2 games with the same number of players
return general
else:
return gnames
@utils.func_timer()
def get_alias(g, settings):
std_aliases = {
"League of Legends": "LoL",
"Counter-Strike: Global Offensive": "CS:GO",
"Team Fortress 2": "TF2",
"Grand Theft Auto V": "GTAV",
"PLAYERUNKNOWN'S BATTLEGROUNDS": "PUBG",
"MONSTER HUNTER: WORLD": "MH:W",
"The Elder Scrolls V: Skyrim": "Skyrim",
"The Elder Scrolls V: Skyrim Special Edition": "Skyrim",
"The Elder Scrolls Online": "ESO",
"Tom Clancy's Rainbow Six Siege": "Rainbow Six Siege",
"FINAL FANTASY XIV": "FFXIV",
"FINAL FANTASY XIV Online": "FFXIV",
"Warhammer End Times Vermintide": "Vermintide 1",
"Warhammer: Vermintide 2": "Vermintide 2",
"World of Warcraft Classic": "WoW Classic",
"World of Warcraft": "WoW",
"Call of Dutyː Modern Warfare": "CoDːMW",
"Call of Duty®️ː Modern Warfare®️": "CoDːMW",
}
if g in settings["aliases"]:
g = settings["aliases"][g]
elif g in std_aliases:
g = std_aliases[g]
return g
@utils.func_timer()
def get_game_name(channel, games):
settings = utils.get_serv_settings(channel.guild)
general = ["General"] if "general" not in settings else [settings["general"]]
if games == general:
return games[0]
for i, g in enumerate(games):
games[i] = get_alias(g, settings)
tmp = games
games = []
for g in tmp:
if g not in games:
games.append(g)
return ", ".join(games)
@utils.func_timer()
def get_party_info(channel, game, asip, default=""):
settings = utils.get_serv_settings(channel.guild)
parties = {}
states = {}
details = {}
num_playing = {}
sizes = {}
sneakies = 0
for m in channel.members:
act = m.activity
act_name = get_alias(act.name, settings) if act else None
if act and act_name == game:
pid = -1
if hasattr(act, "party") and act.party:
if "id" in act.party:
pid = act.party["id"]
if pid == -1:
# No party ID is given, so we make our own based on other info
pid = act_name
if hasattr(act, "party") and act.party:
if "size" in act.party:
pid += "/".join(str(v) for v in act.party["size"])
if hasattr(act, "state") and act.state:
pid += act.state
if hasattr(act, "details") and act.details:
pid += act.details
if hasattr(act, "state") and act.state:
states[pid] = act.state
if hasattr(act, "details") and act.details:
details[pid] = act.details
if hasattr(act, "party") and act.party:
if "size" in act.party:
num_playing[pid] = str(act.party["size"][0])
try:
sizes[pid] = str(act.party["size"][1])
except IndexError:
sizes[pid] = "0"
parties[pid] = parties[pid] + 1 if pid in parties else 1
elif not act and asip:
sneakies += 1
biggest_party = [None, 0]
for p, v in parties.items():
if v > biggest_party[1]:
biggest_party = [p, v]
pid, players = biggest_party
info = {
"state": default,
"details": default,
"rich": False,
"sneakies": "0",
"num_playing": "0",
"size": "0",
}
if pid is not None:
info["state"] = states[pid] if pid in states else default
info["details"] = details[pid] if pid in details else default
info["rich"] = pid in states or pid in details
info["sneakies"] = sneakies
if pid in num_playing:
info["num_playing"] = num_playing[pid]
else:
info["num_playing"] = str(players + sneakies)
if pid in sizes:
info["size"] = sizes[pid]
elif channel.user_limit:
info["size"] = str(channel.user_limit)
return info
@utils.func_timer()
async def update_bitrate(channel, settings, user_left=None, reset=False):
if "custom_bitrates" not in settings:
return False
custom_bitrates = []
for m in channel.members:
if str(m.id) in settings["custom_bitrates"]:
custom_bitrates.append(settings["custom_bitrates"][str(m.id)])
if not custom_bitrates:
if reset or (user_left and str(user_left.id) in settings["custom_bitrates"]):
p = utils.get_primary_channel(channel.guild, settings, channel)
bitrate = p.bitrate
else:
return False
else:
bitrate = min(channel.guild.bitrate_limit, mean(custom_bitrates) * 1000)
if bitrate == channel.bitrate:
return False
await channel.edit(bitrate=bitrate)
return bitrate
@utils.func_timer()
async def update_text_channel_role(guild, member, channel, mode):
if mode == "leave" and len(channel.members) <= 0:
return # Last person leaving, channel will be deleted, no need to update roles
settings = utils.get_serv_settings(guild)
for p, pv in settings["auto_channels"].items():
for s, sv in pv["secondaries"].items():
if s == channel.id:
if "tcr" in sv:
r = guild.get_role(sv["tcr"])
if r:
if mode == "join":
await member.add_roles(r)
elif mode == "leave":
try:
await member.remove_roles(r)
except discord.errors.NotFound:
pass # It's possible someone joins too quick and the role doesn't exist yet?
# Ensure existing members have the role in case they joined too quickly
members = [m for m in channel.members if m != member]
for m in members:
if r not in m.roles:
await m.add_roles(r)
return
@utils.func_timer()
async def dm_user(user, msg, embed=None, error=True):
if user is None:
log("Failed to DM unknown user.")
return
if user.dm_channel is None:
await user.create_dm()
try:
last_message = await user.dm_channel.history(limit=1).flatten()
except discord.errors.Forbidden:
log("Forbidden to get user dm_history {}".format(user.id))
return
if len(last_message) > 0:
last_message = last_message[0]
else:
last_message = None
if error and last_message and last_message.id in cfg.DM_ERROR_MESSAGES:
return
try:
m = await user.dm_channel.send(content=msg, embed=embed)
if error:
cfg.DM_ERROR_MESSAGES[m.id] = time()
except discord.errors.Forbidden:
log("Forbidden to DM user {}".format(user.id))
@utils.func_timer()
async def echo(msg, channel, user=None):
max_chars = 1950 # Discord has a character limit of 2000 per message. Use 1950 to be safe.
msg = str(msg)
if len(msg) > max_chars:
chunks = list([msg[i : i + max_chars] for i in range(0, len(msg), max_chars)])
else:
chunks = [msg]
for c in chunks:
try:
await channel.send(c)
except discord.errors.Forbidden:
log("Forbidden to echo", channel.guild)
if user:
await dm_user(
user,
"I don't have permission to send messages in the "
"`#{}` channel of **{}**.".format(channel.name, channel.guild.name),
)
return False
except AttributeError:
log("Can't echo to voice channel", channel.guild)
if user and isinstance(channel, discord.VoiceChannel):
await dm_user(user, c)
return False
except Exception:
log("Failed to echo", channel.guild)
print(traceback.format_exc())
return False
return True
@utils.func_timer()
async def blind_echo(msg, guild):
settings = utils.get_serv_settings(guild)
msg_channel = None
last_message = None
if "last_channel" in settings:
msg_channel = guild.get_channel(settings["last_channel"])
if msg_channel:
last_message = msg_channel.last_message
if not msg_channel:
server_contact = guild.get_member(settings["server_contact"])
if server_contact is not None:
if server_contact.dm_channel is None:
await server_contact.create_dm()
msg_channel = server_contact.dm_channel
last_message = await msg_channel.history(limit=1).flatten()
if len(last_message) > 0:
last_message = last_message[0]
if msg_channel:
if last_message and last_message.id in cfg.ERROR_MESSAGES:
# Don't spam multiple error messages in a row
return
try:
m = await msg_channel.send(msg)
except:
settings["last_channel"] = 0 # Don't try use this channel in future
utils.set_serv_settings(guild, settings)
return
cfg.ERROR_MESSAGES[m.id] = time()
@utils.func_timer()
async def admin_log(msg, client, important=False):
admin = client.get_user(cfg.CONFIG["admin_id"])
if admin.dm_channel is None:
await admin.create_dm()
mention = admin.mention
if important and len(msg + "\n" + mention) <= 2000:
msg = msg + "\n" + mention
admin_channel = admin.dm_channel
if "admin_channel" in cfg.CONFIG:
admin_channel = client.get_channel(cfg.CONFIG["admin_channel"])
await admin_channel.send(msg)
@utils.func_timer()
async def log_timings(client, highlight):
text = ""
if highlight is not None:
text = "**{0}** took {1:.2f}s".format(highlight, cfg.TIMINGS[highlight])
log(text.replace("**", ""))
text += "\n" + utils.format_timings()
await admin_log(text, client)
@utils.func_timer()
async def server_log(guild, msg, msg_level, settings=None):
if settings is None:
settings = utils.get_serv_settings(guild)
if "logging" not in settings or settings["logging"] is False:
return
log_level = settings["log_level"]
if msg_level > log_level:
return
if not is_gold(guild):
return
if msg_level == 3 and not is_sapphire(guild):
return
try:
channel = guild.get_channel(settings["logging"])
except:
# Channel no longer exists, or we can't get it, either way we can't log anything.
return
try:
msg = msg.replace("➕", "+") # Make the default plus sign more visible
await channel.send(msg)
except discord.errors.Forbidden:
log("Forbidden to log", guild)
except Exception:
log("Failed to log", guild)
print(traceback.format_exc())
return
@utils.func_timer()
async def check_patreon(force_update=False, client=None):
if patreon_info is None:
return
print("Checking Patreon...{}".format(" (F)" if force_update else ""))
previous_patrons = deepcopy(cfg.PATRONS)
patrons = patreon_info.fetch_patrons(force_update=force_update)
if client and previous_patrons and patrons != previous_patrons:
for p, r in patrons.items():
if p not in previous_patrons:
pu = client.get_user(p)
try:
pn = pu.display_name
except AttributeError:
pn = "<UNKNOWN>"
important = True if r in ["sapphire", "diamond"] else False
await admin_log("🎉 New {} patron! **{}** (`{}`)".format(cfg.TIER_ICONS[r], pn, p), client, important)
msg = (
"🎉 **Thanks for your support!** 🎉\nTo activate your patron-exclusive features, "
"simply run `@me power-overwhelming` in your server."
)
if r in ["sapphire", "diamond"]:
msg += "\n\nGive me a few hours to set up your private "
msg += "bot" if r == "sapphire" else "server"
msg += ", and then I'll contact you in the support server to make the switch."
if r == "diamond":
msg += (
"\nPlease let me know whether you prefer a server in Europe, "
"North America or Asia by replying to this message."
)
await dm_user(pu, msg)
for p, r in previous_patrons.items():
if p not in patrons and p != cfg.CONFIG["admin_id"]:
pu = client.get_user(p)
try:
pn = pu.display_name
except AttributeError:
pn = "<UNKNOWN>"
important = True if r in ["sapphire", "diamond"] else False
await admin_log("😱 Lost {} patron! **{}** (`{}`)".format(cfg.TIER_ICONS[r], pn, p), client, important)
patreon_info.update_patron_servers(patrons)
print("{} patrons".format(len(patrons)))
@utils.func_timer()
def is_gold(guild):
if patreon_info is None:
return True
gold_servers = [
607246684367618049, # T4
]
if isinstance(guild, int):
guild_id = guild
else:
guild_id = guild.id
gold_servers += cfg.GOLD_SERVERS
return guild_id in gold_servers or is_sapphire(guild_id)
@utils.func_timer()
def is_sapphire(guild):
if patreon_info is None:
return True
sapphire_servers = [
332246283601313794, # Salt Sanc
601015720200896512, # Dots Bots
460459401086763010, # T1
607246539101831168, # T2
]
if isinstance(guild, int):
guild_id = guild
else:
guild_id = guild.id
sapphire_servers += cfg.SAPPHIRE_SERVERS
return guild_id in sapphire_servers
@utils.func_timer()
def get_sapphire_id(guild):
for s, sv in cfg.CONFIG["sapphires"].items():
if guild.id in sv["servers"]:
return int(s)
return None
@utils.func_timer()
async def power_overwhelming(ctx, auth_guilds):
author = ctx["message"].author
r = "Checking..."
success = False
m = await ctx["channel"].send(r)
if patreon_info is None:
return False, "No need to do that."
patrons = patreon_info.fetch_patrons(force_update=False)
patrons[cfg.CONFIG["admin_id"]] = "sapphire"
auth_path = os.path.join(cfg.SCRIPT_DIR, "patron_auths.json")
if author.id in patrons:
reward = patrons[author.id].title()
max_guilds = {"Gold": 2, "Sapphire": 5, "Diamond": 50}
if isinstance(auth_guilds, list) and len(auth_guilds) > max_guilds[reward]:
return False, (
"Sorry, {0} patrons can only enable {0} features in up to {1} servers.".format(
reward, max_guilds[reward]
)
)
auths = utils.read_json(auth_path)
str_uid = str(author.id)
prev_auths = auths[str_uid]["servers"] if str_uid in auths else []
if isinstance(auth_guilds, list): # Possibly multiple guilds specified, command run in DM
auths[str_uid] = {"servers": auth_guilds}
guilds = [ctx["client"].get_guild(g) for g in auth_guilds]
else: # Single guild specified, command run in server
auths[str_uid] = {"servers": [auth_guilds.id]}
guilds = [auth_guilds]
if cfg.SAPPHIRE_ID is not None:
config = utils.get_config()
if author.id != config["sapphires"][str(cfg.SAPPHIRE_ID)]["initiator"]:
return False, "This bot doesn't belong to you."
config["sapphires"][str(cfg.SAPPHIRE_ID)]["servers"] = [g.id for g in guilds]
utils.set_config(config)
cfg.CONFIG = config
utils.write_json(auth_path, auths, indent=4)
patreon_info.update_patron_servers(patrons)
success = True
r = ""
for g in guilds:
await admin_log(
"🔑 Authenticated **{}**'s {} server {} `{}`".format(author.name, reward, g.name, g.id),
ctx["client"],
important=False,
)
r += "\n✅ Nice! *{}* is now a **{}** server.".format(g.name, reward)
for a in prev_auths:
if a not in [g.id for g in guilds]:
r += "\n❗ Removed authentication from `{}`.".format(a)
if reward in ["Diamond", "Sapphire"] and cfg.SAPPHIRE_ID is None:
r += (
"\nPlease give me ~{} hours to set up your private bot - "
"I'll DM you when it's ready to make the swap!".format(12 if reward == "Sapphire" else 24)
)
else:
await admin_log("🔒 Failed to authenticate for **{}** `{}`".format(author.name, author.id), ctx["client"])
r = (
"❌ Sorry it doesn't look like you're a Patron.\n"
"If you just recently became one, please make sure you've connected your discord account "
"(<https://bit.ly/2UdfYbQ>) and try again in a few minutes. "
"If it still doesn't work, let me know in the support server: <https://discord.io/DotsBotsSupport>."
)
await m.edit(content=r)
return success, "NO RESPONSE"
@utils.func_timer()
def get_guilds(client):
guilds = []
am_sapphire_bot = cfg.SAPPHIRE_ID is not None
am_gold_bot = "gold_id" in cfg.CONFIG and client.user.id == cfg.CONFIG["gold_id"]
for g in client.guilds:
if g is not None and g.name is not None:
if am_sapphire_bot:
if is_sapphire(g) and g.id in cfg.CONFIG["sapphires"][str(cfg.SAPPHIRE_ID)]["servers"]:
guilds.append(g)
elif am_gold_bot:
if is_gold(g):
guilds.append(g)
else:
if not is_sapphire(g) or get_sapphire_id(g) is None:
guilds.append(g)
return guilds
@utils.func_timer()
async def react(message, r):
try:
await message.add_reaction(r)
except discord.errors.Forbidden:
return False
except discord.errors.NotFound:
return False
return True
@utils.func_timer()
async def custom_name(guild, c, u, n):
settings = utils.get_serv_settings(guild)
for p, pv in settings["auto_channels"].items():
for s, sv in pv["secondaries"].items():
if s == c.id:
if n.lower() == "reset":
del settings["auto_channels"][p]["secondaries"][s]["name"]
else:
if "uniquenames" in settings and settings["uniquenames"]:
existing_names = []
for t_p, t_pv in settings["auto_channels"].items():
for t_s, t_sv in t_pv["secondaries"].items():
if "name" in t_sv and t_s != c.id:
existing_names.append(t_sv["name"])
if n in existing_names:
return False, "That name is already used by another channel, please pick another."
settings["auto_channels"][p]["secondaries"][s]["name"] = n
utils.set_serv_settings(guild, settings)
await server_log(
guild,
':regional_indicator_n: {} (`{}`) changed the channel (`{}`) name to "{}"'.format(
user_hash(u), u.id, c.id, esc_md(n)
),
2,
settings,
)
return True, None
@utils.func_timer()
async def set_creator(guild, cid, creator):
settings = utils.get_serv_settings(guild)
for p, pv in settings["auto_channels"].items():
for s, sv in pv["secondaries"].items():
if s == cid:
settings["auto_channels"][p]["secondaries"][s]["creator"] = creator.id
try:
jc = guild.get_channel(settings["auto_channels"][p]["secondaries"][s]["jc"])
await jc.edit(name="⇩ Join {}".format(creator.display_name))
except (KeyError, AttributeError):
pass
if s in cfg.PRIV_CHANNELS:
cfg.PRIV_CHANNELS[s]["creator"] = creator
break
utils.set_serv_settings(guild, settings)
return True
@utils.func_timer(1.5)
async def rename_channel(guild, channel, settings, primary_id, templates=None, i=-1, ignore_lock=False):
if not settings:
settings = utils.get_serv_settings(guild)
if ignore_lock and not channel.members:
# Sometimes channel.members doesn't update immediately after moving user into it.
await asyncio.sleep(1)
channel = guild.get_channel(channel.id)
if not templates:
templates = {}
if "template" in settings["auto_channels"][primary_id]:
try:
templates[channel.id] = settings["auto_channels"][primary_id]["template"]
except AttributeError:
return # channel has no ID
if channel.members and (ignore_lock or not channel_is_requested(channel)):
if channel.id in templates:
cname = templates[channel.id]
else:
cname = settings["channel_name_template"]
guild_is_gold = is_gold(guild)
guild_is_sapphire = is_sapphire(guild)
has_expression = "{{" in cname and "}}" in cname and cname.count("{{") == cname.count("}}") and guild_is_gold
is_private = settings["priv"] if "priv" in settings else False
cname = cname.replace("@@num_players@@", "@@num_playing@@") # Common mistake
if "@@game_name@@" in cname or "@@party_" in cname or "@@num_playing@@" in cname or has_expression:
games = get_channel_games(channel)
gname = get_game_name(channel, games)
if "@@party_" in cname or "@@num_playing@@" in cname or has_expression:
party = get_party_info(channel, gname, settings["asip"] if "asip" in settings else False)
if (
"@@creator@@" in cname
or ("general" in settings and "@@creator@@" in settings["general"])
or "@@num_others@@" in cname
or "@@stream_name@@" in cname
or has_expression
or is_private
):
creator = None
creator_name = "Unknown"
creator_id = utils.get_creator_id(settings, channel)
if creator_id:
creator_found = False
for m in channel.members:
if m.id == creator_id:
creator_found = True
creator = m
creator_name = utils.get_display_name(settings, m)
break
if not creator_found: # Creator not in channel anymore, use top member
members = [m for m in channel.members if not m.bot]
if members:
creator = sorted(members, key=lambda x: x.display_name.lower())[0]
await set_creator(guild, channel.id, creator)
creator_name = utils.get_display_name(settings, creator)
creator_id = creator.id
else:
# Only time we can get here is if a bot is the last one in the channel,
# meaning it'll be deleted very soon and we can skip renaming it.
return
i_str = str(i + 1)
if i == -1:
i_str = "?"
cname = cname.replace("##", "#" + i_str)
cname = cname.replace("+#", roman.toRoman(int(i + 1)))
for x in range(5):
cname = cname.replace("${}#".format("0" * x), i_str.zfill(x + 1))
random_set = 0
while (
guild_is_gold
and "[[" in cname
and "]]" in cname
and ("/" in cname.split("[[", 1)[1].split("]]", 1)[0] or "\\" in cname.split("[[", 1)[1].split("]]", 1)[0])
):
seed_c = channel.id + random_set
seed_d = cfg.SEED + channel.id + random_set
b, m = cname.split("[[", 1)
m, e = m.split("]]", 1)
if "\\" in m:
words = m.split("\\")
seed(seed_d)
m = choice(words)
else:
words = m.split("/")
seed(seed_c)
m = choice(words)
cname = b + m + e
random_set += 1
if "@@nato@@" in cname and guild_is_gold:
nato = [
"Alpha",
"Bravo",
"Charlie",
"Delta",
"Echo",
"Foxtrot",
"Golf",
"Hotel",
"India",
"Juliett",
"Kilo",
"Lima",
"Mike",
"November",
"Oscar",
"Papa",
"Quebec",
"Romeo",
"Sierra",
"Tango",
"Uniform",
"Victor",
"Whiskey",
"X Ray",
"Yankee",
"Zulu",
]
if i < len(nato):
nato = nato[i]
else:
nato = nato[i % len(nato)] + " " + str(ceil((i + 1) / len(nato)))
cname = cname.replace("@@nato@@", nato)
if "@@num@@" in cname:
members = [m for m in channel.members if not m.bot]
cname = cname.replace("@@num@@", str(len(members)))
if "@@num_playing@@" in cname and guild_is_sapphire:
cname = cname.replace("@@num_playing@@", party["num_playing"])
if "@@party_size@@" in cname and guild_is_sapphire:
cname = cname.replace("@@party_size@@", party["size"])
if "@@party_state@@" in cname and guild_is_sapphire:
cname = cname.replace("@@party_state@@", party["state"])
if "@@party_details@@" in cname and guild_is_sapphire:
cname = cname.replace("@@party_details@@", party["details"])
others = -1
if "@@num_others@@" in cname:
others = len([m for m in channel.members if (not m.bot and m.id != creator_id)])
cname = cname.replace("@@num_others@@", str(others))
while (
"<<" in cname
and ">>" in cname
and ("/" in cname.split("<<", 1)[1].split(">>", 1)[0] or "\\" in cname.split("<<", 1)[1].split(">>", 1)[0])
):
b, m = cname.split("<<", 1)
m, e = m.split(">>", 1)
c = None
if m.count("/") == 1:
c = "/"
n = len([m for m in channel.members if not m.bot])
elif m.count("\\") == 1:
c = "\\"
if others == -1:
n = len(
[m for m in channel.members if (not m.bot and m.id != utils.get_creator_id(settings, channel))]
)
else:
n = others
if c is not None:
s, p = m.split(c, 1)
if n == 1:
m = s
else:
m = p
cname = b + m + e
if "@@bitrate@@" in cname and guild_is_gold:
cname = cname.replace("@@bitrate@@", "{}kbps".format(round(channel.bitrate / 1000)))
while "{{" in cname and "}}" in cname and cname.count("{{") == cname.count("}}") and guild_is_gold:
m, e = cname.split("}}", 1)
sections = m.split("{{")
b = "{{".join(sections[:-1])
m = sections[-1]
m = utils.eval_expression(m, guild_is_sapphire, creator, party, gname)
cname = b + m + e
if "@@game_name@@" in cname:
cname = cname.replace("@@game_name@@", gname)
if "@@creator@@" in cname:
cname = cname.replace("@@creator@@", creator_name)
if "@@stream_name@@" in cname:
stream_name = ""
for act in creator.activities:
if act.type == discord.ActivityType.streaming:
stream_name = act.name
break
cname = cname.replace("@@stream_name@@", stream_name)
while '""' in cname and cname.count('""') % 2 == 0 and ":" in cname.split('""', 1)[1].split('""')[0]:
b, m = cname.split('""', 1)
m, e = m.split('""', 1)
m, s = m.split(":", 1)
s = s.strip()
modes = m.split("+")
ops = {
"caps": str.upper,
"upper": str.upper,
"lower": str.lower,
"title": utils.capitalize,
"swap": str.swapcase,
"rand": utils.random_case,
"usd": utils.upsidedown,
"acro": utils.acronym,
"remshort": utils.remove_short_words,
"spaces": utils.full_strip,
"uwu": translate.uwu,
"scaps": translate.small_caps,
"bold": translate.bold,
"italic": translate.italic,
"bolditalic": translate.bolditalic,
"script": translate.script,
"boldscript": translate.boldscript,
"fraktur": translate.fraktur,
"boldfraktur": translate.boldfraktur,
"double": translate.double,
"sans": translate.sans,
"boldsans": translate.boldsans,
"italicsans": translate.italicsans,
"bolditalicsans": translate.bolditalicsans,
"mono": translate.mono,
}
for mode in modes:
mode = mode.lower().strip()
if mode in ops: