-
Notifications
You must be signed in to change notification settings - Fork 26
/
erm.py
1307 lines (1133 loc) · 55.9 KB
/
erm.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 datetime
import json
import logging
import time
from dataclasses import MISSING
from pkgutil import iter_modules
import re
from collections import defaultdict
try:
import Levenshtein
from fuzzywuzzy import fuzz, process
except ImportError:
from fuzzywuzzy import fuzz, process
import aiohttp
import decouple
import discord.mentions
import motor.motor_asyncio
import asyncio
import pytz
import sentry_sdk
from decouple import config
from discord import app_commands
from discord.ext import tasks
from roblox import client as roblox
from sentry_sdk import push_scope, capture_exception
from sentry_sdk.integrations.pymongo import PyMongoIntegration
from datamodels.CustomFlags import CustomFlags
from datamodels.ServerKeys import ServerKeys
from datamodels.ShiftManagement import ShiftManagement
from datamodels.ActivityNotice import ActivityNotices
from datamodels.Analytics import Analytics
from datamodels.Consent import Consent
from datamodels.CustomCommands import CustomCommands
from datamodels.Errors import Errors
from datamodels.FiveMLinks import FiveMLinks
from datamodels.LinkStrings import LinkStrings
from datamodels.PunishmentTypes import PunishmentTypes
from datamodels.Reminders import Reminders
from datamodels.Settings import Settings
from datamodels.APITokens import APITokens
from datamodels.StaffConnections import StaffConnections
from datamodels.Views import Views
from datamodels.Actions import Actions
from datamodels.Warnings import Warnings
from datamodels.ProhibitedUseKeys import ProhibitedUseKeys
from datamodels.PendingOAuth2 import PendingOAuth2
from datamodels.OAuth2Users import OAuth2Users
from datamodels.IntegrationCommandStorage import IntegrationCommandStorage
from menus import CompleteReminder, LOAMenu, RDMActions
from utils.viewstatemanger import ViewStateManager
from utils.bloxlink import Bloxlink
from utils.prc_api import PRCApiClient
from utils.prc_api import ResponseFailure
from utils.utils import *
from utils.constants import *
import utils.prc_api
setup = False
try:
sentry_url = config("SENTRY_URL")
bloxlink_api_key = config("BLOXLINK_API_KEY")
except decouple.UndefinedValueError:
sentry_url = ""
bloxlink_api_key = ""
discord.utils.setup_logging(level=logging.INFO)
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.voice_states = True
credentials_dict = {}
scope = [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive",
]
class Bot(commands.AutoShardedBot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setup_status: bool = False
async def close(self):
for session in self.external_http_sessions:
if session is not None and session.closed is False:
await session.close()
await super().close()
async def is_owner(self, user: discord.User):
# Only developers of the bot on the team should have
# full access to Jishaku commands. Hard-coded
# IDs are a security vulnerability.
# Else fall back to the original
if user.id == 1165311055728226444:
return True
return await super().is_owner(user)
async def setup_hook(self) -> None:
self.external_http_sessions: list[aiohttp.ClientSession] = []
self.view_state_manager: ViewStateManager = ViewStateManager()
global setup
if not self.setup_status:
# await bot.load_extension('utils.routes')
logging.info(
"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━���━━━━━━\n\n{} is online!".format(
self.user.name
)
)
self.mongo = motor.motor_asyncio.AsyncIOMotorClient(str(mongo_url))
if environment == "DEVELOPMENT":
self.db = self.mongo["erm"]
elif environment == "PRODUCTION":
self.db = self.mongo["erm"]
elif environment == "ALPHA":
self.db = self.mongo['alpha']
else:
raise Exception("Invalid environment")
self.start_time = time.time()
self.shift_management = ShiftManagement(self.db, "shift_management")
self.errors = Errors(self.db, "errors")
self.loas = ActivityNotices(self.db, "leave_of_absences")
self.reminders = Reminders(self.db, "reminders")
self.custom_commands = CustomCommands(self.db, "custom_commands")
self.analytics = Analytics(self.db, "analytics")
self.punishment_types = PunishmentTypes(self.db, "punishment_types")
self.custom_flags = CustomFlags(self.db, "custom_flags")
self.views = Views(self.db, "views")
self.api_tokens = APITokens(self.db, "api_tokens")
self.link_strings = LinkStrings(self.db, "link_strings")
self.fivem_links = FiveMLinks(self.db, "fivem_links")
self.consent = Consent(self.db, "consent")
self.punishments = Warnings(self)
self.settings = Settings(self.db, "settings")
self.server_keys = ServerKeys(self.db, "server_keys")
self.staff_connections = StaffConnections(self.db, "staff_connections")
self.ics = IntegrationCommandStorage(self.db, 'logged_command_data')
self.actions = Actions(self.db, "actions")
self.prohibited = ProhibitedUseKeys(self.db, "prohibited_keys")
self.pending_oauth2 = PendingOAuth2(self.db, "pending_oauth2")
self.oauth2_users = OAuth2Users(self.db, "oauth2")
self.roblox = roblox.Client()
self.prc_api = PRCApiClient(self, base_url=config('PRC_API_URL', default='https://api.policeroleplay.community/v1'), api_key=config('PRC_API_KEY', default='default_api_key'))
self.bloxlink = Bloxlink(self, config('BLOXLINK_API_KEY'))
Extensions = [m.name for m in iter_modules(["cogs"], prefix="cogs.")]
Events = [m.name for m in iter_modules(["events"], prefix="events.")]
BETA_EXT = ["cogs.StaffConduct"]
EXTERNAL_EXT = ["utils.api"]
[Extensions.append(i) for i in EXTERNAL_EXT]
for extension in Extensions:
try:
if extension not in BETA_EXT:
await self.load_extension(extension)
logging.info(f"Loaded {extension}")
elif environment == "DEVELOPMENT" or environment == "ALPHA":
await self.load_extension(extension)
logging.info(f"Loaded {extension}")
except Exception as e:
logging.error(f"Failed to load extension {extension}.", exc_info=e)
for extension in Events:
try:
await self.load_extension(extension)
logging.info(f"Loaded {extension}")
except Exception as e:
logging.error(f"Failed to load extension {extension}.", exc_info=e)
bot.error_list = []
logging.info("Connected to MongoDB!")
# await bot.load_extension("jishaku")
await bot.load_extension("utils.hot_reload")
# await bot.load_extension('utils.server')
if not bot.is_synced: # check if slash commands have been synced
bot.tree.copy_global_to(guild=discord.Object(id=987798554972143728))
if environment == "DEVELOPMENT":
await bot.tree.sync(guild=discord.Object(id=987798554972143728))
else:
pass
# Prevent auto syncing
# await bot.tree.sync()
# guild specific: leave blank if global (global registration can take 1-24 hours)
bot.is_synced = True
check_reminders.start()
check_loa.start()
iterate_ics.start()
# GDPR.start()
iterate_prc_logs.start()
statistics_check.start()
tempban_checks.start()
check_whitelisted_car.start()
change_status.start()
logging.info("Setup_hook complete! All tasks are now running!")
async for document in self.views.db.find({}):
if document["view_type"] == "LOAMenu":
for index, item in enumerate(document["args"]):
if item == "SELF":
document["args"][index] = self
loa_id = document['args'][3]
if isinstance(loa_id, dict):
loa_expiry = loa_id['expiry']
if loa_expiry < datetime.datetime.now().timestamp():
await self.views.delete_by_id(document['_id'])
continue
self.add_view(
LOAMenu(*document["args"]), message_id=document["message_id"]
)
self.setup_status = True
bot = Bot(
command_prefix=get_prefix,
case_insensitive=True,
intents=intents,
help_command=None,
allowed_mentions=discord.AllowedMentions(
replied_user=False, everyone=False, roles=False
),
)
bot.debug_servers = [987798554972143728]
bot.is_synced = False
bot.shift_management_disabled = False
bot.punishments_disabled = False
bot.bloxlink_api_key = bloxlink_api_key
environment = config("ENVIRONMENT", default="DEVELOPMENT")
internal_command_storage = {}
def running():
if bot:
if bot._ready != MISSING:
return 1
else:
return -1
else:
return -1
@bot.before_invoke
async def AutoDefer(ctx: commands.Context):
internal_command_storage[ctx] = datetime.datetime.now(tz=pytz.UTC).timestamp()
if ctx.command:
if ctx.command.extras.get("ephemeral") is True:
if ctx.interaction:
return await ctx.defer(ephemeral=True)
if ctx.command.extras.get("ignoreDefer") is True:
return
await ctx.defer()
@bot.after_invoke
async def loggingCommandExecution(ctx: commands.Context):
if ctx in internal_command_storage:
command_name = ctx.command.qualified_name
duration = float(datetime.datetime.now(tz=pytz.UTC).timestamp() - internal_command_storage[ctx])
logging.info(f"Command {command_name} was run by {ctx.author.name} ({ctx.author.id}) and lasted {duration} seconds")
shard_info = f"Shard ID ::: {ctx.guild.shard_id}" if ctx.guild else "Shard ID ::: -1, Direct Messages"
logging.info(shard_info)
else:
logging.info("Command could not be found in internal context storage. Please report.")
del internal_command_storage[ctx]
client = roblox.Client()
async def staff_check(bot_obj, guild, member):
guild_settings = await bot_obj.settings.find_by_id(guild.id)
if guild_settings:
if "role" in guild_settings["staff_management"].keys():
if guild_settings["staff_management"]["role"] != "":
if isinstance(guild_settings["staff_management"]["role"], list):
for role in guild_settings["staff_management"]["role"]:
if role in [role.id for role in member.roles]:
return True
elif isinstance(guild_settings["staff_management"]["role"], int):
if guild_settings["staff_management"]["role"] in [
role.id for role in member.roles
]:
return True
if member.guild_permissions.manage_messages:
return True
return False
async def management_check(bot_obj, guild, member):
guild_settings = await bot_obj.settings.find_by_id(guild.id)
if guild_settings:
if "management_role" in guild_settings["staff_management"].keys():
if guild_settings["staff_management"]["management_role"] != "":
if isinstance(
guild_settings["staff_management"]["management_role"], list
):
for role in guild_settings["staff_management"]["management_role"]:
if role in [role.id for role in member.roles]:
return True
elif isinstance(
guild_settings["staff_management"]["management_role"], int
):
if guild_settings["staff_management"]["management_role"] in [
role.id for role in member.roles
]:
return True
if member.guild_permissions.manage_guild:
return True
return False
async def admin_check(bot_obj, guild, member):
guild_settings = await bot_obj.settings.find_by_id(guild.id)
if guild_settings:
if "admin_role" in guild_settings["staff_management"].keys():
if guild_settings["staff_management"]["admin_role"] != "":
if isinstance(guild_settings["staff_management"]["admin_role"], list):
for role in guild_settings["staff_management"]["admin_role"]:
if role in [role.id for role in member.roles]:
return True
elif isinstance(guild_settings["staff_management"]["admin_role"], int):
if guild_settings["staff_management"]["admin_role"] in [role.id for role in member.roles]:
return True
if "management_role" in guild_settings["staff_management"].keys():
if guild_settings["staff_management"]["management_role"] != "":
if isinstance(guild_settings["staff_management"]["management_role"], list):
for role in guild_settings["staff_management"]["management_role"]:
if role in [role.id for role in member.roles]:
return True
elif isinstance(guild_settings["staff_management"]["management_role"], int):
if guild_settings["staff_management"]["management_role"] in [role.id for role in member.roles]:
return True
if member.guild_permissions.administrator:
return True
return False
async def staff_predicate(ctx):
if ctx.guild is None:
return True
else:
return await staff_check(ctx.bot, ctx.guild, ctx.author)
def is_staff():
return commands.check(staff_predicate)
async def admin_predicate(ctx):
if ctx.guild is None:
return True
else:
return await admin_check(ctx.bot, ctx.guild, ctx.author)
def is_admin():
return commands.check(admin_predicate)
async def management_predicate(ctx):
if ctx.guild is None:
return True
else:
return await management_check(ctx.bot, ctx.guild, ctx.author)
def is_management():
return commands.check(management_predicate)
async def check_privacy(bot: Bot, guild: int, setting: str):
privacySettings = await bot.privacy.find_by_id(guild)
if not privacySettings:
return True
if not setting in privacySettings.keys():
return True
return privacySettings[setting]
async def warning_json_to_mongo(jsonName: str, guildId: int):
with open(f"{jsonName}", "r") as f:
logging.info(f)
f = json.load(f)
logging.info(f)
for key, value in f.items():
structure = {"_id": key.lower(), "warnings": []}
logging.info([key, value])
logging.info(key.lower())
if await bot.warnings.find_by_id(key.lower()):
data = await bot.warnings.find_by_id(key.lower())
for item in data["warnings"]:
structure["warnings"].append(item)
for item in value:
item.pop("ID", None)
item["id"] = next(generator)
item["Guild"] = guildId
structure["warnings"].append(item)
logging.info(structure)
if await bot.warnings.find_by_id(key.lower()) == None:
await bot.warnings.insert(structure)
else:
await bot.warnings.update(structure)
bot.erm_team = {
"i_imikey": "Bot Developer",
"mbrinkley": "First Community Manager - Removed",
"theoneandonly_5567": "Executive Manager",
"royalcrests": "Website Developer & Asset Designer",
"1friendlydoge": "Data Scientist - a friendly doge",
}
async def staff_field(bot: Bot, embed, query):
flag = await bot.flags.find_by_id(query)
embed.add_field(
name="<:ERMAdmin:1111100635736187011> Flags",
value=f"<:Space:1100877460289101954><:ERMArrow:1111091707841359912>{flag['rank']}",
inline=False,
)
return embed
bot.warning_json_to_mongo = warning_json_to_mongo
# include environment variables
if environment == "PRODUCTION":
bot_token = config("PRODUCTION_BOT_TOKEN")
logging.info("Using production token...")
elif environment == "DEVELOPMENT":
try:
bot_token = config("DEVELOPMENT_BOT_TOKEN")
except decouple.UndefinedValueError:
bot_token = ""
logging.info("Using development token...")
elif environment == "ALPHA":
try:
bot_token = config('ALPHA_BOT_TOKEN')
except decouple.UndefinedValueError:
bot_token = ""
logging.info('Using ERM V4 Alpha token...')
else:
raise Exception("Invalid environment")
try:
mongo_url = config("MONGO_URL", default=None)
except decouple.UndefinedValueError:
mongo_url = ""
# status change discord.ext.tasks
@tasks.loop(hours=1)
async def change_status():
await bot.wait_until_ready()
logging.info("Changing status")
status = "⚡ /about | ermbot.xyz"
await bot.change_presence(
activity=discord.CustomActivity(name=status)
)
@tasks.loop(minutes=1)
async def check_reminders():
try:
async for guildObj in bot.reminders.db.find({}):
new_go = await bot.reminders.db.find_one(guildObj)
g_id = new_go['_id']
for item in new_go["reminders"].copy():
try:
if item.get("paused") is True:
continue
if not new_go.get('_id'):
new_go['_id'] = g_id
dT = datetime.datetime.now()
interval = item["interval"]
tD = dT + datetime.timedelta(seconds=interval)
if tD.timestamp() - item["lastTriggered"] >= interval:
guild = bot.get_guild(int(guildObj["_id"]))
if not guild:
continue
channel = guild.get_channel(int(item["channel"]))
if not channel:
continue
roles = []
try:
for role in item["role"]:
roles.append(guild.get_role(int(role)).mention)
except TypeError:
roles = [""]
if (
item.get("completion_ability")
and item.get("completion_ability") is True
):
view = CompleteReminder()
else:
view = None
embed = discord.Embed(
title="Notification",
description=f"{item['message']}",
color=BLANK_COLOR,
)
lastTriggered = tD.timestamp()
item["lastTriggered"] = lastTriggered
await bot.reminders.update_by_id(new_go)
if isinstance(item.get('integration'), dict):
# This has the ERLC integration enabled
command = 'h' if item['integration']['type'] == 'Hint' else ('m' if item['integration']['type'] == 'Message' else None)
content = item['integration']['content']
total = ':' + command + ' ' + content
if await bot.server_keys.db.count_documents({'_id': channel.guild.id}) != 0:
do_not_complete = False
try:
status = await bot.prc_api.get_server_status(channel.guild.id)
except prc_api.ResponseFailure as e:
do_not_complete = True
# print(status)
if not do_not_complete:
resp = await bot.prc_api.run_command(channel.guild.id, total)
if resp[0] != 200:
logging.info('Failed reaching PRC due to {} status code'.format(resp))
else:
logging.info('Integration success with 200 status code')
else:
logging.info(f'Cancelled execution of reminder for {channel.guild.id} - {e.status_code}')
if not view:
await channel.send(" ".join(roles), embed=embed,
allowed_mentions = discord.AllowedMentions(
replied_user=True, everyone=True, roles=True, users=True
))
else:
await channel.send(" ".join(roles), embed=embed, view=view,
allowed_mentions=discord.AllowedMentions(
replied_user=True, everyone=True, roles=True, users=True
))
except Exception as e:
# print(e)
pass
except Exception as e:
# print(e)
pass
@tasks.loop(minutes=1, reconnect=True)
async def tempban_checks():
# This will check for expired time bans
# and for servers which have this feature enabled
# to automatically remove the ban in-game
# using POST /server/command
# This will also use a GET request before
# sending that POST request, particularly
# GET /server/bans
# We also check if the punishment item is
# before the update date, because else we'd
# have too high influx of invalid
# temporary bans
# For diagnostic purposes, we also choose to
# capture the amount of time it takes for this
# event to run, as it may cause issues in
# time registration.
cached_servers = {}
initial_time = time.time()
async for punishment_item in bot.punishments.db.find({
"Epoch": {"$gt": 1709164800},
"CheckExecuted": {"$exists": False},
"UntilEpoch": {"$lt": int(datetime.datetime.now(tz=pytz.UTC).timestamp())},
"Type": "Temporary Ban"
}):
try:
await bot.fetch_guild(punishment_item['Guild'])
except discord.HTTPException:
continue
if not cached_servers.get(punishment_item['Guild']):
try:
cached_servers[punishment_item['Guild']] = await bot.prc_api.fetch_bans(punishment_item['Guild'])
except:
continue
punishment_item['CheckExecuted'] = True
await bot.punishments.update_by_id(punishment_item)
if punishment_item['UserID'] not in [i.user_id for i in cached_servers[punishment_item['Guild']]]:
continue
sorted_punishments = sorted([i async for i in bot.punishments.db.find({"UserID": punishment_item['UserID'], "Guild": punishment_item['Guild']})], key=lambda x: x['Epoch'], reverse=True)
new_sorted_punishments = []
for item in sorted_punishments:
if item == punishment_item:
break
new_sorted_punishments.append(item)
if any([i['Type'] in ["Ban", "Temporary Ban"] for i in new_sorted_punishments]):
continue
await bot.prc_api.unban_user(punishment_item['Guild'], punishment_item['user_id'])
del cached_servers
end_time = time.time()
logging.warning('Event tempban_checks took {} seconds'.format(str(end_time - initial_time)))
async def update_channel(guild, channel_id, stat, placeholders):
try:
format_string = stat["format"]
channel_id = int(channel_id)
channel = await fetch_get_channel(guild, channel_id)
if channel:
for key, value in placeholders.items():
format_string = format_string.replace(f"{{{key}}}", str(value))
await channel.edit(name=format_string)
logging.info(f"Updated channel {channel_id} in guild {guild.id}")
else:
logging.error(f"Channel {channel_id} not found in guild {guild.id}")
except Exception as e:
logging.error(f"Failed to update channel {channel_id} in guild {guild.id}: {e}", exc_info=True)
async def fetch_get_channel(target, identifier):
channel = target.get_channel(identifier)
if not channel:
try:
channel = await target.fetch_channel(identifier)
except discord.HTTPException as e:
channel = None
return channel
@tasks.loop(seconds=45, reconnect=True)
async def statistics_check():
initial_time = time.time()
async for guild_data in bot.settings.db.find({}):
guild_id = guild_data['_id']
try:
guild = await bot.fetch_guild(guild_id)
except discord.errors.NotFound:
continue
settings = await bot.settings.find_by_id(guild_id)
if not settings or "ERLC" not in settings or "statistics" not in settings["ERLC"]:
continue
statistics = settings["ERLC"]["statistics"]
try:
players: list[Player] = await bot.prc_api.get_server_players(guild_id)
status: ServerStatus = await bot.prc_api.get_server_status(guild_id)
queue: int = await bot.prc_api.get_server_queue(guild_id, minimal=True)
except prc_api.ResponseFailure:
logging.error(f"PRC ResponseFailure for guild {guild_id}")
continue
on_duty = await bot.shift_management.shifts.db.count_documents({'Guild': guild_id, 'EndEpoch': 0})
moderators = len(list(filter(lambda x: x.permission == 'Server Moderator', players)))
admins = len(list(filter(lambda x: x.permission == 'Server Administrator', players)))
staff_ingame = len(list(filter(lambda x: x.permission != 'Normal', players)))
current_player = status.current_players
join_code = status.join_key
max_players = status.max_players
logging.info(f"Updating statistics for guild {guild_id}")
placeholders = {
"onduty": on_duty,
"staff": staff_ingame,
"mods": moderators,
"admins": admins,
"players": current_player,
"join_code": join_code,
"max_players": max_players,
"queue": queue
}
tasks = [update_channel(guild, channel_id, stat_value, placeholders) for channel_id, stat_value in statistics.items()]
await asyncio.gather(*tasks)
end_time = time.time()
logging.warning(f"Event statistics_check took {end_time - initial_time} seconds")
async def run_command(guild_id, username, message):
while True:
command = f":pm {username} {message}"
command_response = await bot.prc_api.run_command(guild_id, command)
if command_response[0] == 200:
logging.info(f"Sent PM to {username} in guild {guild_id}")
break
elif command_response[0] == 429:
retry_after = int(command_response[1].get('Retry-After', 5))
logging.warning(f"Rate limited. Retrying after {retry_after} seconds.")
await asyncio.sleep(retry_after)
else:
logging.error(f"Failed to send PM to {username} in guild {guild_id}")
break
def is_whitelisted(vehicle_name, whitelisted_vehicle):
vehicle_year_match = re.search(r'\d{4}$', vehicle_name)
whitelisted_year_match = re.search(r'\d{4}$', whitelisted_vehicle)
if vehicle_year_match and whitelisted_year_match:
vehicle_year = vehicle_year_match.group()
whitelisted_year = whitelisted_year_match.group()
if vehicle_year != whitelisted_year:
return False
vehicle_name_base = vehicle_name[:vehicle_year_match.start()].strip()
whitelisted_vehicle_base = whitelisted_vehicle[:whitelisted_year_match.start()].strip()
return fuzz.ratio(vehicle_name_base.lower(), whitelisted_vehicle_base.lower()) > 80
return False
async def get_player_avatar_url(player_id):
url = f"https://thumbnails.roblox.com/v1/users/avatar?userIds={player_id}&size=180x180&format=Png&isCircular=false"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
data = await response.json()
return data['data'][0]['imageUrl']
pm_counter = {}
@tasks.loop(minutes=2, reconnect=True)
async def check_whitelisted_car():
initial_time = time.time()
async for items in bot.settings.db.find(
{"ERLC.vehicle_restrictions.enabled": {"$exists": True, "$eq": True}}
):
guild_id = items['_id']
try:
guild = await bot.fetch_guild(guild_id)
except discord.errors.NotFound:
continue
try:
whitelisted_vehicle_roles = items['ERLC'].get('vehicle_restrictions').get('roles')
alert_channel_id = items['ERLC'].get('vehicle_restrictions').get('channel')
whitelisted_vehicles = items['ERLC'].get('vehicle_restrictions').get('cars', [])
alert_message = items["ERLC"].get("vehicle_restrictions").get('message', "You do not have the required role to use this vehicle. Switch it or risk being moderated.")
except KeyError:
logging.error(f"KeyError for guild {guild_id}")
continue
if not whitelisted_vehicle_roles or not alert_channel_id:
logging.warning(f"Skipping guild {guild_id} due to missing whitelisted vehicle roles or alert channel.")
continue
if isinstance(whitelisted_vehicle_roles, int):
exotic_roles = [guild.get_role(whitelisted_vehicle_roles)]
elif isinstance(whitelisted_vehicle_roles, list):
exotic_roles = [guild.get_role(role_id) for role_id in whitelisted_vehicle_roles if guild.get_role(role_id)]
else:
logging.warning(f"Invalid whitelisted_vehicle_roles data: {whitelisted_vehicle_roles}")
continue
alert_channel = bot.get_channel(alert_channel_id)
if not alert_channel:
try:
alert_channel = await bot.fetch_channel(alert_channel_id)
except discord.HTTPException:
alert_channel = None
logging.warning(f"Alert channel not found for guild {guild_id}")
continue
if not exotic_roles or not alert_channel:
logging.warning(f"Exotic role or alert channel not found for guild {guild_id}.")
continue
try:
players: list[Player] = await bot.prc_api.get_server_players(guild_id)
vehicles: list[prc_api.ActiveVehicle] = await bot.prc_api.get_server_vehicles(guild_id)
except prc_api.ResponseFailure:
logging.error(f"PRC ResponseFailure for guild {guild_id}")
continue
logging.info(f"Found {len(vehicles)} vehicles in guild {guild_id}")
logging.info(f"Found {len(players)} players in guild {guild_id}")
matched = {}
for item in vehicles:
for x in players:
if x.username == item.username:
matched[item] = x
for vehicle, player in matched.items():
whitelisted = False
for whitelisted_vehicle in whitelisted_vehicles:
if is_whitelisted(vehicle.vehicle, whitelisted_vehicle):
whitelisted = True
break
pattern = re.compile(re.escape(player.username), re.IGNORECASE)
member_found = False
for member in guild.members:
if pattern.search(member.name) or pattern.search(member.display_name) or (hasattr(member, 'global_name') and member.global_name and pattern.search(member.global_name)):
member_found = True
has_exotic_role = False
for role in exotic_roles:
if role in member.roles:
has_exotic_role = True
break
if not has_exotic_role:
logging.debug(f"Player {player.username} does not have the required role for their whitelisted vehicle.")
await run_command(guild_id, player.username, alert_message)
if player.username not in pm_counter:
pm_counter[player.username] = 1
logging.debug(f"PM Counter for {player.username}: 1")
else:
pm_counter[player.username] += 1
logging.debug(f"PM Counter for {player.username}: {pm_counter[player.username]}")
if pm_counter[player.username] >= 4:
logging.info(f"Sending warning embed for {player.username} in guild {guild.name}")
try:
embed = discord.Embed(
title="Whitelisted Vehicle Warning",
description=f"""
> Player [{player.username}](https://roblox.com/users/{player.id}/profile) has been PMed 3 times to obtain the required role for their whitelisted vehicle.
""",
color=RED_COLOR,
timestamp=datetime.datetime.now(tz=pytz.UTC)
).set_footer(
text=f"Guild: {guild.name} | Powered by ERM Systems",
).set_thumbnail(
url=await get_player_avatar_url(player.id)
)
await alert_channel.send(embed=embed)
except discord.HTTPException as e:
logging.error(f"Failed to send embed for {player.username} in guild {guild.name}: {e}")
logging.info(f"Removing {player.username} from PM counter")
pm_counter.pop(player.username)
break
elif member_found == False:
logging.debug(f"Member with username {player.username} not found in guild {guild.name}.")
await run_command(guild_id, player.username, alert_message)
if player.username not in pm_counter:
pm_counter[player.username] = 1
logging.debug(f"PM Counter for {player.username}: 1")
else:
pm_counter[player.username] += 1
logging.debug(f"PM Counter for {player.username}: {pm_counter[player.username]}")
if pm_counter[player.username] >= 4:
logging.info(f"Sending warning embed for {player.username} in guild {guild.name}")
try:
embed = discord.Embed(
title="Whitelisted Vehicle Warning",
description=f"""
> Player [{player.username}](https://roblox.com/users/{player.id}/profile) has been PMed 3 times to obtain the required role for their whitelisted vehicle.
""",
color=RED_COLOR,
timestamp=datetime.datetime.now(tz=pytz.UTC)
).set_footer(
text=f"Guild: {guild.name} | Powered by ERM Systems",
).set_thumbnail(
url=await get_player_avatar_url(player.id)
)
await alert_channel.send(embed=embed)
except discord.HTTPException as e:
logging.error(f"Failed to send embed for {player.username} in guild {guild.name}: {e}")
logging.info(f"Removing {player.username} from PM counter")
pm_counter.pop(player.username)
break
else:
continue
del matched
end_time = time.time()
logging.warning(f"Event check_whitelisted_car took {end_time - initial_time} seconds")
class LogTracker:
def __init__(self):
self.last_timestamps = defaultdict(lambda: defaultdict(int))
def get_last_timestamp(self, guild_id: int, log_type: str) -> int:
return self.last_timestamps[guild_id][log_type]
def update_timestamp(self, guild_id: int, log_type: str, timestamp: int):
self.last_timestamps[guild_id][log_type] = max(
timestamp,
self.last_timestamps[guild_id][log_type]
)
log_tracker = LogTracker()
@tasks.loop(minutes=10, reconnect=True)
async def iterate_prc_logs():
try:
server_count = await bot.settings.db.aggregate([
{
'$match': {
'ERLC': {'$exists': True},
'$or': [
{'ERLC.rdm_channel': {'$type': 'long', '$ne': 0}},
{'ERLC.kill_logs': {'$type': 'long', '$ne': 0}},
{'ERLC.player_logs': {'$type': 'long', '$ne': 0}}
]
}
},
{
'$lookup': {
'from': 'server_keys',
'localField': '_id',
'foreignField': '_id',
'as': 'server_key'
}
},
{
'$match': {
'server_key': {'$ne': []}
}
},
{
'$count': 'total'
}
]).to_list(1)
server_count = server_count[0]['total'] if server_count else 0
logging.warning(f"[ITERATE] Starting iteration for {server_count} servers")
processed = 0
start_time = time.time()
batch_size = 15
pipeline = [
{
'$match': {
'ERLC': {'$exists': True},
'$or': [
{'ERLC.rdm_channel': {'$type': 'long', '$ne': 0}},
{'ERLC.kill_logs': {'$type': 'long', '$ne': 0}},
{'ERLC.player_logs': {'$type': 'long', '$ne': 0}}
]
}
},
{
'$lookup': {
'from': 'server_keys',
'localField': '_id',
'foreignField': '_id',
'as': 'server_key'
}
},
{
'$match': {
'server_key': {'$ne': []}
}
}
]
async def send_log_batch(channel, embeds):
if not embeds:
return
# Split embeds into chunks of 10 (Discord's limit)
for i in range(0, len(embeds), 10):
chunk = embeds[i:i+10]
try:
await channel.send(embeds=chunk)
except discord.HTTPException as e:
logging.error(f"Failed to send log batch: {e}")
def process_kill_logs(kill_logs, last_timestamp):
"""Process kill logs and return embeds"""
embeds = []
latest_timestamp = last_timestamp
for log in sorted(kill_logs):
if log.timestamp <= last_timestamp:
continue
latest_timestamp = max(latest_timestamp, log.timestamp)
embed = discord.Embed(
title="Kill Log",
color=BLANK_COLOR,
description=f"[{log.killer_username}](https://roblox.com/users/{log.killer_user_id}/profile) killed [{log.killed_username}](https://roblox.com/users/{log.killed_user_id}/profile) • <t:{int(log.timestamp)}:T>"
)
embeds.append(embed)
return embeds, latest_timestamp
def process_player_logs(player_logs, last_timestamp):
"""Process player logs and return embeds"""
embeds = []
latest_timestamp = last_timestamp