-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1589 lines (1209 loc) · 62.7 KB
/
main.py
File metadata and controls
1589 lines (1209 loc) · 62.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
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 discord
from discord.ext import commands, tasks
from pydantic import BaseModel, Field
from ruamel.yaml import YAML
import logging
import asyncpg
import asyncio
from perms import get_user_staff_perms
from kittycat import StaffPermissions, has_perm, Permission
import secrets
import traceback
import sys
import os
import datetime
import io
import importlib
import uvicorn
import aiohttp
from typing import Callable
from PIL import Image, ImageDraw, ImageFont
from cfg_autogen import gen_config
from migrations import MIGRATION_LIST, Migration
from constants import BOTS_ROLE_PERMS
MAX_PER_CACHE_SERVER = 40
logging.basicConfig(level=logging.INFO)
class NeededBots(BaseModel):
id: int
name: str
invite: str
class CacheServerMaker(BaseModel):
client_id: int
client_secret: str
token: str
class Config(BaseModel):
token: str
postgres_url: str = Field(default="postgresql:///infinity")
pinned_servers: list[int] = Field(default=[870950609291972618, 758641373074423808])
main_server: int = Field(default=758641373074423808)
needed_bots: list[NeededBots] = Field(
default=[
NeededBots(
name = "Borealis",
id = 1200677946789212242,
invite = "https://discord.com/api/oauth2/authorize?client_id={id}&permissions=8&scope=bot%20applications.commands"
),
NeededBots(
name = "Arcadia",
id = 870728078228324382,
invite = "https://discord.com/api/oauth2/authorize?client_id={id}&scope=bot%20applications.commands"
),
NeededBots(
name = "Popplio",
id = 815553000470478850,
invite = "https://discord.com/api/oauth2/authorize?client_id={id}&scope=bot%20applications.commands"
)
]
)
notify_webhook: str
base_url: str
cache_server_maker: CacheServerMaker
borealis_client_id: int
borealis_client_secret: str
gen_config(Config, 'config.yaml.sample')
yaml = YAML(typ="safe")
with open("config.yaml", "r") as f:
config = Config(**yaml.load(f))
with open("guild_logo.png", "rb") as f:
guild_logo = f.read()
class BorealisBot(commands.AutoShardedBot):
pool: asyncpg.pool.Pool
def __init__(self, config: Config):
super().__init__(command_prefix="#", intents=discord.Intents.all())
self.config = config
self.pool = None
async def run_bot(self):
self.session = aiohttp.ClientSession()
self.pool = await asyncpg.pool.create_pool(self.config.postgres_url)
api = importlib.import_module("api")
api.bot = bot
api.config = config
self.bloop = asyncio.get_event_loop()
server = uvicorn.Server(config=uvicorn.Config(api.app, workers=3, loop=self.bloop, port=2837, host="0.0.0.0"))
asyncio.create_task(server.serve())
await super().start(self.config.token)
await cache_server_bot.start(config.cache_server_maker.token)
intents = discord.Intents.all()
bot = BorealisBot(config)
cache_server_bot = discord.Client(intents=discord.Intents.all())
have_started_events = False
bot_tasks = []
# On ready handler
@bot.event
async def on_ready():
print(f"Logged in as {bot.user.name}#{bot.user.discriminator} ({bot.user.id})")
if not have_started_events:
bot_tasks.extend(
[
validate_members,
ensure_invites,
ensure_cache_servers,
nuke_not_approved,
ensure_guild_image,
main_server_kicker,
task_fail_check,
]
)
for t in bot_tasks:
t.add_exception_type(Exception)
t.start()
@bot.command()
async def register(ctx: commands.Context):
try:
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
except:
usp = StaffPermissions(user_positions=[], perm_overrides=[])
resolved = []
if not resolved:
return await ctx.send("User is not a staff member")
if not has_perm(resolved, Permission.from_str("borealis.register")):
return await ctx.send("You need ``borealis.register`` permission to perform migrations!")
await bot.tree.sync()
await ctx.send("Done!")
@tasks.loop(seconds=10)
async def task_fail_check():
for task in bot_tasks:
if task.failed():
print(f"task_fail_check: Task has failed {task}, restarting")
task.cancel()
task.start()
print(f"task_fail_check: Restarted task {task}")
@cache_server_bot.event
async def on_ready():
for guild in cache_server_bot.guilds:
if guild.owner_id == cache_server_bot.user.id:
await guild.delete()
else:
await guild.leave()
async def create_cache_server(guild: discord.Guild):
# Check that we're not already in a cache server
count = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(guild.id))
if count:
return False
oauth_md = await bot.pool.fetchrow("SELECT owner_id from cache_server_oauth_md")
if guild.id in bot.config.pinned_servers:
return False
if str(guild.owner_id) != oauth_md["owner_id"]:
return False
done_bots = []
needed_bots_members: list[discord.Member] = []
for b in bot.config.needed_bots:
member = guild.get_member(b.id)
if member:
done_bots.append(b.name)
needed_bots_members.append(member)
continue
not_yet_added = list(filter(lambda b: b.name not in done_bots, bot.config.needed_bots))
if not not_yet_added:
if not guild.me.guild_permissions.administrator:
raise Exception("Please give Borealis administrator in order to continue")
# Create the 'Needed Bots' role
needed_bots_role = await guild.create_role(name="System Bots", permissions=discord.Permissions(administrator=True), color=discord.Color.blurple(), hoist=True)
hs_role = await guild.create_role(name="Holding Staff", permissions=discord.Permissions(administrator=True), color=discord.Color.blurple(), hoist=True)
webmod_role = await guild.create_role(name="Web Moderator", permissions=discord.Permissions(manage_guild=True, kick_members=True, ban_members=True, moderate_members=True), color=discord.Color.green(), hoist=True)
bots_role = await guild.create_role(name="Bots", permissions=BOTS_ROLE_PERMS, color=discord.Color.brand_red(), hoist=True)
await guild.me.add_roles(needed_bots_role, bots_role)
for m in needed_bots_members:
await m.add_roles(needed_bots_role, bots_role)
welcome_category = await guild.create_category("Welcome")
welcome_channel = await welcome_category.create_text_channel("welcome")
invite = await welcome_channel.create_invite(reason="Cache server invite", unique=True, max_uses=0, max_age=0)
logs_category = await guild.create_category('Logging')
logs_channel = await logs_category.create_text_channel('system-logs')
await bot.pool.execute("INSERT INTO cache_servers (guild_id, bots_role, web_moderator_role, system_bots_role, logs_channel, staff_role, welcome_channel, invite_code, name) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", str(guild.id), str(bots_role.id), str(webmod_role.id), str(needed_bots_role.id), str(logs_channel.id), str(hs_role.id), str(welcome_channel.id), invite.code, guild.name)
async with aiohttp.ClientSession() as session:
hook = discord.Webhook.from_url(bot.config.notify_webhook, session=session)
await hook.send(content=f"@Bot Reviewers\n\nCache server added: {guild.name} ({guild.id}) {invite.url}")
for member in guild.members:
await handle_member(member, cache_server_info={"bots_role": bots_role.id, "web_moderator_role": str(webmod_role.id), "system_bots_role": needed_bots_role.id, "logs_channel": logs_channel.id, "staff_role": hs_role.id})
return True
else:
raise Exception(f"The following bots have not been added to the server yet: {', '.join([f'{b.id} ({b.name})' for b in not_yet_added])}")
async def resolve_guilds_from_str(guilds: str, check: Callable[[discord.Guild], bool]):
"""
If guilds is 'all', return all guilds that the bot is in and passes check(g)
If guilds is 'cs', then return all cache servers the bot is in and passes check(g)
Otherwise, returns all guilds from the comma seperated list that passes check(g)
"""
resolved_guilds: list[discord.Guild] = []
if guilds == "all":
resolved_guilds = [g for g in bot.guilds if check(g) and g.id not in bot.config.pinned_servers]
elif guilds == "cs":
db_ids = await bot.pool.fetch("SELECT guild_id from cache_servers")
for g in db_ids:
guild = bot.get_guild(int(g["guild_id"]))
if guild and check(guild):
resolved_guilds.append(guild)
else:
for id in guilds.split(","):
id = id.strip()
guild = None
for g in bot.guilds:
if id == str(g.id) or id == g.name:
guild = g
break
if not guild:
continue
if guild and check(guild):
resolved_guilds.append(guild)
return resolved_guilds
async def refresh_oauth(cred: dict):
# Check if expired, if so, refresh access token and update db
if cred["expires_at"] < datetime.datetime.now(tz=datetime.timezone.utc):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
"grant_type": "refresh_token",
"refresh_token": cred["refresh_token"],
"client_id": config.borealis_client_id if cred["bot"] == "borealis" else config.cache_server_maker.client_id,
"client_secret": config.borealis_client_secret if cred["bot"] == "borealis" else config.cache_server_maker.client_secret,
}
print(data)
async with bot.session.post(f"https://discord.com/api/v10/oauth2/token", data=data, headers=headers) as resp:
if resp.status != 200:
err = await resp.text()
raise Exception(f"Failed to refresh token for {cred['user_id']} {resp.status} {err}")
data = await resp.json()
await bot.pool.execute("UPDATE cache_server_oauths SET access_token = $1, refresh_token = $2, expires_at = $3 WHERE user_id = $4", data["access_token"], data["refresh_token"], datetime.datetime.now() + datetime.timedelta(seconds=data["expires_in"]), cred["user_id"])
return {
"user_id": cred["user_id"],
"access_token": data["access_token"],
"refresh_token": data["refresh_token"],
}
return {
"user_id": cred["user_id"],
"access_token": cred["access_token"],
"refresh_token": cred["refresh_token"],
}
async def create_unprovisioned_cache_server():
await cache_server_bot.wait_until_ready()
oauth_md = await bot.pool.fetchrow("SELECT owner_id from cache_server_oauth_md")
if not oauth_md:
raise Exception("Oauth metadata not setup, please run #cs_oauth_mdset to set owner id for new cache servers")
_oauth_creds = await bot.pool.fetch("SELECT user_id, access_token, refresh_token, expires_at, bot from cache_server_oauths WHERE bot = 'doxycycline'")
oauth_creds = []
for cred in _oauth_creds:
usp = await get_user_staff_perms(bot.pool, int(cred["user_id"]))
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.make_cache_servers")):
continue # Don't add this user
oauth_creds.append(await refresh_oauth(cred))
guild: discord.Guild = await cache_server_bot.create_guild(name="IBLCS-" + secrets.token_hex(4))
# Add owner first to transfer ownership
owner_creds = None
for cred in oauth_creds:
if cred["user_id"] == oauth_md["owner_id"]:
owner_creds = cred
break
if not owner_creds:
raise Exception("Owner credentials not found")
async with aiohttp.ClientSession() as session:
# First add owner
async with session.put(f"https://discord.com/api/v10/guilds/{guild.id}/members/{owner_creds['user_id']}", headers={"Authorization": f"Bot {config.cache_server_maker.token}"}, json={"access_token": owner_creds["access_token"]}) as resp:
if not resp.ok:
raise Exception(f"Failed to add owner to guild: {await resp.text()}")
await asyncio.sleep(1)
# Add all other users
for cred in oauth_creds:
if cred["user_id"] == owner_creds["user_id"]:
continue
async with session.put(f"https://discord.com/api/v10/guilds/{guild.id}/members/{cred['user_id']}", headers={"Authorization": f"Bot {config.cache_server_maker.token}"}, json={"access_token": cred["access_token"]}) as resp:
if not resp.ok:
raise Exception(f"Failed to add user to guild: {await resp.text()}")
await asyncio.sleep(1)
# create oauthadmin role
oauth_admin_role = await guild.create_role(name="Oauth Admin", permissions=discord.Permissions.all(), color=discord.Color.blurple(), hoist=True)
# Give all users oauthadmin role
async for member in guild.fetch_members():
await member.add_roles(oauth_admin_role)
# Send everyone ping to temp channel
temp_chan = await guild.create_text_channel("temp")
await temp_chan.send(
f"@everyone"
)
msg = f"""
New unprovisioned cache server created!
Add the following bots to the server:
"""
for b in bot.config.needed_bots:
invite = b.invite.replace("{id}", str(b.id)).replace("{perms}", "8")
msg += f"\n- {b.name}: [{invite}]\n"
msg += "\n3. Run the following command in the server: ``#make_cache_server true``"
await temp_chan.send(msg)
# Transfer ownership and leave
await guild.edit(owner=discord.Object(int(owner_creds["user_id"])))
await guild.leave()
async def handle_member(member: discord.Member, cache_server_info):
"""
Handles a member, including adding them to any needed roles
This is a seperate function to allow for better debugging using the WIP fastapi webserver
"""
if not member.bot:
try:
usp = await get_user_staff_perms(bot.pool, member.id)
except:
usp = None
if usp and cache_server_info:
webmod_role = member.guild.get_role(int(cache_server_info["web_moderator_role"]))
staff_role = member.guild.get_role(int(cache_server_info["staff_role"]))
if not webmod_role:
async with aiohttp.ClientSession() as session:
hook = discord.Webhook.from_url(bot.config.notify_webhook, session=session)
await hook.send(content=f"Failed to find web moderator role for staff member {member.name} ({member.id}). The web moderator role currently configured is {cache_server_info['web_moderator_role']}. Please verify this role exists <@&{cache_server_info['staff_role']}>")
return
if not staff_role:
async with aiohttp.ClientSession() as session:
hook = discord.Webhook.from_url(bot.config.notify_webhook, session=session)
await hook.send(content=f"Failed to find staff role for staff member {member.name} ({member.id}). The staff role currently configured is {cache_server_info['staff_role']}. Please verify this role exists <@&{cache_server_info['staff_role']}>")
return
if len(usp.user_positions) == 0:
if staff_role in member.roles:
await member.remove_roles(staff_role)
if webmod_role in member.roles:
await member.remove_roles(webmod_role)
else:
# Add webmod role
if webmod_role not in member.roles:
await member.add_roles(webmod_role)
resolved_perms = usp.resolve()
if has_perm(resolved_perms, Permission.from_str("borealis.can_have_staff_role")):
if staff_role not in member.roles:
await member.add_roles(staff_role)
else:
if staff_role in member.roles:
await member.remove_roles(staff_role)
# If still not found...
if not cache_server_info:
# Ignore non-cache servers
return
if member.bot:
# Check if the bot is in the needed bots list
if str(member.id) in [str(b.id) for b in bot.config.needed_bots]:
# Give Needed Bots role and Bots role
needed_bots_role = member.guild.get_role(int(cache_server_info["system_bots_role"]))
bots_role = member.guild.get_role(int(cache_server_info["bots_role"]))
if not needed_bots_role or not bots_role:
# Send alert to logs channel
logs_channel = member.guild.get_channel(int(cache_server_info["logs_channel"]))
if logs_channel:
await logs_channel.send(f"Failed to find needed roles for needed bot {member.name} ({member.id}). The Needed Bots role currently configured is {cache_server_info['system_bots_role']} and the Bots role is {cache_server_info['bots_role']}. Please verify these roles exist <@&{cache_server_info['staff_role']}>")
return
# Check if said bot has the needed roles
if needed_bots_role not in member.roles or bots_role not in member.roles:
# Add the roles
return await member.add_roles(needed_bots_role, bots_role)
return
# Check if this bot has been selected for this cache server
count = await bot.pool.fetchval("SELECT COUNT(*) from cache_server_bots WHERE guild_id = $1 AND bot_id = $2", str(member.guild.id), str(member.id))
if not count:
# Not white-listed, kick it
return await member.kick(reason="Not white-listed for cache server")
# Also, check that the bot is approved or certified
bot_type = await bot.pool.fetchval("SELECT type from bots WHERE bot_id = $1", str(member.id))
if bot_type and bot_type not in ["approved", "certified"]:
# Not approved or certified, kick it
await bot.pool.execute("DELETE FROM cache_server_bots WHERE guild_id = $1 AND bot_id = $2", str(member.guild.id), str(member.id))
return await member.kick(reason="Not approved or certified")
# Add the bot to the Bots role
bots_role = member.guild.get_role(int(cache_server_info["bots_role"]))
if not bots_role:
# Send alert to logs channel
logs_channel = member.guild.get_channel(int(cache_server_info["logs_channel"]))
if logs_channel:
await logs_channel.send(f"Failed to find Bots role for bot {member.name} ({member.id}). The Bots role currently configured is {cache_server_info['bots_role']}. Please verify this role exists <@&{cache_server_info['staff_role']}>")
return
if bots_role not in member.roles:
await member.add_roles(bots_role)
async def remove_if_tresspassing(member: discord.Member):
"""Removes a bot from the main server if it is not premium, certified or explicitly whitelisted or a partner"""
if member.guild.id != bot.config.main_server:
raise Exception("Not main server")
if not member.bot:
raise Exception("Not a bot")
whitelist_entry = await bot.pool.fetchval("SELECT COUNT(*) from bot_whitelist WHERE bot_id = $1", str(member.id))
if whitelist_entry:
return
bot_entry = await bot.pool.fetchval("SELECT COUNT(*) from bots WHERE bot_id = $1 AND (premium = true OR type = 'certified')", str(member.id))
if bot_entry:
return
# Partner check
partner_entry = await bot.pool.fetchval("SELECT COUNT(*) FROM partners WHERE bot_id = $1", str(member.id))
if partner_entry:
return
if member.top_role >= member.guild.me.top_role:
print("Cant kick", member.name, member.top_role, member.guild.me.top_role)
await member.kick(reason="Not premium, certified or whitelisted")
@bot.event
async def on_member_join(member: discord.Member):
if member.guild.id == bot.config.main_server and member.bot:
try:
await remove_if_tresspassing(member)
except Exception as exc:
print(f"on_member_join [bot_tresspass_check] (id={member},{member.id}) {exc}")
return
cache_server_info = await bot.pool.fetchrow("SELECT bots_role, system_bots_role, logs_channel, staff_role, web_moderator_role from cache_servers WHERE guild_id = $1", str(member.guild.id))
if not cache_server_info:
try:
res = await create_cache_server(member.guild)
if not res:
print(f"Not making cache server for {member.guild.name} ({member.guild.id}) [failed checks]")
except Exception as exc:
print(f"Not making cache server for {member.guild.name} ({member.guild.id}) due to reason: {exc}")
else:
await handle_member(member, cache_server_info=cache_server_info)
@tasks.loop(minutes=5)
async def main_server_kicker():
print(f"Starting main_server_kicker task on {datetime.datetime.now()}")
main_server = bot.get_guild(bot.config.main_server)
if not main_server:
print("Bot could not find main server")
return
for member in main_server.members:
if member.bot and member.id != bot.user.id:
try:
await remove_if_tresspassing(member)
except Exception as exc:
print(f"main_server_kicker (bot_id={member},{member.id}) {exc}")
@tasks.loop(minutes=5)
async def nuke_not_approved():
print (f"Starting nuke_not_approved task on {datetime.datetime.now()}")
# Get all bots that are not approved or certified
not_approved = await bot.pool.fetch("SELECT bot_id, guild_id from cache_server_bots WHERE bot_id NOT IN (SELECT bot_id from bots WHERE type = 'approved' OR type = 'certified')")
for b in not_approved:
# Delete it first
await bot.pool.execute("DELETE FROM cache_server_bots WHERE bot_id = $1", b["bot_id"])
guild = bot.get_guild(int(b["guild_id"]))
if guild:
member = guild.get_member(int(b["bot_id"]))
if member:
await member.kick(reason="Not approved or certified")
@tasks.loop(minutes=120)
async def ensure_guild_image():
print(f"Starting ensure_guild_image task on {datetime.datetime.now()}")
for guild in bot.guilds:
cache_server_info = await bot.pool.fetchrow("SELECT guild_id from cache_servers WHERE guild_id = $1", str(guild.id))
if not cache_server_info:
continue
name = guild.name.split("-")[-1]
try:
print("Editing guild logo for", name)
# Draw name on guild_logo
img = Image.open(io.BytesIO(guild_logo))
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("Roboto-MediumItalic.ttf", 66)
draw.text((img.width/7, (3.75/6)*img.height), name, (10, 10, 10), font=font, stroke_width=1)
bio = io.BytesIO()
img.save(bio, format="PNG")
bio.seek(0, 0)
# Try writing file to disk for validation
with open(f"guild_logo_{guild.name}.png", "wb") as f:
f.write(bio.read())
bio.seek(0, 0)
await guild.edit(icon=bio.read())
await asyncio.sleep(30)
except Exception as e:
print(f"Failed to edit guild logo for {name}: {e}")
_ensure_cache_server = {} # delete if fail check 3 times
@tasks.loop(minutes=5)
async def ensure_cache_servers():
print(f"Starting ensure_cache_servers task on {datetime.datetime.now()}")
# First ensure only one row of cache_server_oauth_md exists
count = await bot.pool.fetchval("SELECT COUNT(*) from cache_server_oauth_md")
if count > 1:
await bot.pool.execute("DELETE FROM cache_server_oauth_md WHERE id NOT IN (SELECT id from cache_server_oauth_md ORDER BY id DESC LIMIT 1)")
# Check for guilds we are not in
unknown_guilds = await bot.pool.fetch("SELECT guild_id from cache_servers WHERE guild_id != ALL($1)", [str(g.id) for g in bot.guilds])
for guild in unknown_guilds:
print(f"ALERT: Found unknown server {guild['guild_id']}")
c = _ensure_cache_server.get(guild["guild_id"], 0)
if c > 3:
await bot.pool.execute("DELETE FROM cache_servers WHERE guild_id = $1", guild["guild_id"])
_ensure_cache_server[guild["guild_id"]] = c + 1
@tasks.loop(minutes=15)
async def ensure_invites():
"""Task to ensure and correct guild invites for all servers"""
print(f"Starting ensure_invites task on {datetime.datetime.now()}")
for guild in bot.guilds:
cache_server_info = await bot.pool.fetchrow("SELECT welcome_channel, logs_channel, invite_code from cache_servers WHERE guild_id = $1", str(guild.id))
if not cache_server_info:
continue
print(f"Validating invites for {guild.name} ({guild.id})")
invites = await guild.invites()
have_invite = False
for invite in invites:
if invite.code == cache_server_info["invite_code"]:
have_invite = True
else:
if not invite.expires_at:
await invite.delete(reason="Unlimited invites are not allowed on cache servers")
if not have_invite:
logs_channel = guild.get_channel(int(cache_server_info["logs_channel"]))
if not logs_channel:
print(f"Failed to find logs channel for {guild.name} ({guild.id})")
continue
welcome_channel = guild.get_channel(int(cache_server_info["welcome_channel"]))
if not welcome_channel:
print(f"Failed to find welcome channel for {guild.name} ({guild.id})")
await logs_channel.send("Failed to find welcome channel, creating new one")
welcome_channel = await guild.create_text_channel("welcome", reason="Welcome channel")
await bot.pool.execute("UPDATE cache_servers SET welcome_channel = $1 WHERE guild_id = $2", str(welcome_channel.id), str(guild.id))
await logs_channel.send("Cache server invite has expired, creating new one")
invite = await welcome_channel.create_invite(reason="Cache server invite", unique=True, max_uses=0, max_age=0)
await bot.pool.execute("UPDATE cache_servers SET invite_code = $1 WHERE guild_id = $2", invite.code, str(guild.id))
@tasks.loop(minutes=5)
async def validate_members():
"""Task to validate all members every 5 minutes"""
print(f"Starting validate_members task on {datetime.datetime.now()}")
for guild in bot.guilds:
cache_server_info = await bot.pool.fetchrow("SELECT bots_role, system_bots_role, logs_channel, staff_role, web_moderator_role, name from cache_servers WHERE guild_id = $1", str(guild.id))
if not cache_server_info:
if guild.id in bot.config.pinned_servers:
continue
if os.environ.get("DELETE_GUILDS", "false").lower() == "true":
print(f"ALERT: Found unknown server {guild.name} ({guild.id}), leaving/deleting")
try:
if guild.owner_id == bot.user.id:
print(f"ALERT: Guild owner is bot, deleting guild")
await guild.delete()
else:
print(f"ALERT: Guild owner is not bot, leaving guild")
await guild.leave()
except discord.HTTPException:
print(f"ALERT: Failed to leave/delete guild {guild.name} ({guild.id})")
continue
else:
# Check name
if not cache_server_info["name"]:
await bot.pool.execute("UPDATE cache_servers SET name = $1 WHERE guild_id = $2", guild.name, str(guild.id))
elif cache_server_info["name"] != guild.name:
# Update server name
await guild.edit(name=cache_server_info["name"])
print(f"Validating members for {guild.name} ({guild.id})")
for member in guild.members:
if member.id == bot.user.id:
continue
print(f"Validating {member.name} ({member.id}) [bot={member.bot}]")
await handle_member(member, cache_server_info=cache_server_info)
# Error handler
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.CommandNotFound):
return
traceback.print_exception(type(error), error, error.__traceback__, file=sys.stderr)
await ctx.send(f"Error: {error}")
@bot.hybrid_command()
async def db_test(ctx: commands.Context):
await bot.pool.acquire()
await ctx.send("Acquired connection")
@bot.hybrid_command()
async def kittycat(
ctx: commands.Context,
only_show_resolved: bool | None = commands.parameter(default=True, description="Whether to only show resolved permissions or not"),
user_id: int | None = commands.parameter(default=None, description="Whether to only show resolved permissions or not")
):
"""Returns the resolved permissions of the user"""
usp = await get_user_staff_perms(bot.pool, user_id or ctx.author.id)
resolved = [str(p) for p in usp.resolve()]
if only_show_resolved:
await ctx.send(f"**Resolved**: ``{' | '.join(resolved)}``")
else:
await ctx.send(f"**Positions:** {[f'{usp.id} [{usp.index}]' for usp in usp.user_positions]} with overrides: {usp.perm_overrides}\n\n**Resolved**: ``{' | '.join(resolved)}``")
@bot.hybrid_command()
async def cs_createreport(ctx: commands.Context, only_file: bool = False):
"""Create report on all cache servers"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.csreport")):
return await ctx.send("You need ``borealis.csreport`` permission to use this command!")
servers = await bot.pool.fetch("SELECT guild_id, bots_role, system_bots_role, logs_channel, staff_role, welcome_channel, invite_code from cache_servers")
msg = "Cache Servers:\n"
for s in servers:
guild = bot.get_guild(int(s["guild_id"]))
if not guild:
continue
opts = {
"bots_role": guild.get_role(int(s["bots_role"])) or f"{s['bots_role']}, not found",
"system_bots_role": guild.get_role(int(s["system_bots_role"])) or f"{s['system_bots_role']}, not found",
"logs_channel": guild.get_channel(int(s["logs_channel"])) or f"{s['logs_channel']}, not found",
"staff_role": guild.get_role(int(s["staff_role"])) or f"{s['staff_role']}, not found",
"welcome_channel": guild.get_channel(int(s["welcome_channel"])) or f"{s['welcome_channel']}, not found",
"invite_code": s["invite_code"]
}
opts_str = ""
for k, v in opts.items():
opts_str += f"\n- {k}: {v}"
msg += f"\n- {guild.name} ({guild.id})\n{opts_str}"
# Get all bots in cache server
bots = await bot.pool.fetch("SELECT bot_id, guild_id, created_at, added from cache_server_bots")
msg += "\n\n== Bots =="
for b in bots:
if b["guild_id"] == str(guild.id):
name = await bot.pool.fetchval("SELECT username from internal_user_cache__discord WHERE id = $1", b["bot_id"])
msg += f"\n- {name} [{b['bot_id']}]: {b['created_at']} ({b['added']})"
if len(msg) < 1500 and not only_file:
await ctx.send(msg)
else:
# send as file
file = discord.File(filename="cache_servers.txt", fp=io.BytesIO(msg.encode("utf-8")))
await ctx.send(file=file)
async def get_selected_bots(guild_id: int | str):
# Check currently selected too
selected = await bot.pool.fetch("SELECT bot_id, created_at, added from cache_server_bots WHERE guild_id = $1 ORDER BY created_at DESC", str(guild_id))
if len(selected) < MAX_PER_CACHE_SERVER:
# Try selecting other bots and adding it to db
not_yet_selected = await bot.pool.fetch("SELECT bot_id, created_at from bots WHERE (type = 'approved' OR type = 'certified') AND cache_server_uninvitable IS NULL AND bot_id NOT IN (SELECT bot_id from cache_server_bots) ORDER BY RANDOM() DESC LIMIT 50")
for b in not_yet_selected:
if len(selected) >= MAX_PER_CACHE_SERVER:
break
created_at = await bot.pool.fetchval("INSERT INTO cache_server_bots (guild_id, bot_id) VALUES ($1, $2) RETURNING created_at", str(guild_id), b["bot_id"])
selected.append({"bot_id": b["bot_id"], "created_at": created_at, "added": 0})
elif len(selected) > MAX_PER_CACHE_SERVER:
remove_amount = len(selected) - MAX_PER_CACHE_SERVER
to_remove = selected[:remove_amount]
await bot.pool.execute("DELETE FROM cache_server_bots WHERE guild_id = $1 AND bot_id = ANY($2)", str(guild_id), [b["bot_id"] for b in to_remove])
selected = selected[remove_amount:]
return selected
@bot.hybrid_command()
async def cs_allbots(
ctx: commands.Context,
only_not_on_server: bool = True,
only_unfilled_servers: bool = True
):
"""Partitions all bots and sends"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.csallbots")):
return await ctx.send("You need ``borealis.csallbots`` permission to use this command!")
for guild in bot.guilds:
# Check if a cache server
is_cache_server = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(guild.id))
if not is_cache_server:
continue
msg = f"**Cache server: {guild.name} ({guild.id})**"
# Check currently selected too
selected = await get_selected_bots(guild.id)
msg += "\nSelected bots:\n"
showing = 0
for b in selected:
if only_not_on_server:
# Check if in server
in_server = guild.get_member(int(b["bot_id"]))
if in_server:
continue
showing += 1
name = await bot.pool.fetchval("SELECT username from internal_user_cache__discord WHERE id = $1", b["bot_id"])
client_id = await bot.pool.fetchval("SELECT client_id from bots WHERE bot_id = $1", b["bot_id"])
msg += f"\n- {name} [{b['bot_id']}]: https://discord.com/api/oauth2/authorize?client_id={client_id or b['bot_id']}&guild_id={guild.id}&scope=bot ({b['added']}, {b['created_at']})"
if len(msg) >= 1500:
await ctx.send(msg)
msg = ""
if showing or not only_unfilled_servers:
msg += f"\nTotal: {len(selected)} bots\nShowing: {showing} bots"
await ctx.send(msg)
@bot.hybrid_command()
async def cs_bots(ctx: commands.Context, only_show_not_on_server: bool = True):
"""Selects 50 bots for a cache server"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.csbots")):
return await ctx.send("You need ``borealis.csbots`` permission to use this command!")
# Check if a cache server
is_cache_server = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(ctx.guild.id))
if not is_cache_server:
return await ctx.send("This server is not a cache server")
# Check currently selected too
selected = await get_selected_bots(ctx.guild.id)
msg = "Selected bots:\n"
showing = 0
for b in selected:
if only_show_not_on_server:
# Check if in server
in_server = ctx.guild.get_member(int(b["bot_id"]))
if in_server:
continue
showing += 1
name = await bot.pool.fetchval("SELECT username from internal_user_cache__discord WHERE id = $1", b["bot_id"])
client_id = await bot.pool.fetchval("SELECT client_id from bots WHERE bot_id = $1", b["bot_id"])
msg += f"\n- {name} [{b['bot_id']}]: https://discord.com/api/oauth2/authorize?client_id={client_id or b['bot_id']}&guild_id={ctx.guild.id}&scope=bot ({b['added']}, {b['created_at']})"
if len(msg) >= 1500:
await ctx.send(msg)
msg = ""
if msg:
await ctx.send(msg)
await ctx.send(f"Total: {len(selected)} bots\nShowing: {showing} bots")
@bot.hybrid_command()
async def cs_list(
ctx: commands.Context,
):
"""Lists all cache servers, their names, their invites and when they were made"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.cslist")):
return await ctx.send("You need ``borealis.cslist`` permission to use this command!")
servers = await bot.pool.fetch("SELECT guild_id, invite_code, name, created_at from cache_servers")
msg = "Cache Servers:\n"
for s in servers:
bot_count = await bot.pool.fetchval("SELECT COUNT(*) from cache_server_bots WHERE guild_id = $1", s["guild_id"])
msg += f"\n- {s['guild_id']} ({s['name']}) ({bot_count} bots): [{s['invite_code']}, https://discord.gg/{s['invite_code']}] ({s['created_at']})"
if len(msg) >= 1500:
await ctx.send(msg, suppress_embeds=True)
msg = ""
if msg:
await ctx.send(msg, suppress_embeds=True)
await ctx.send(f"Total: {len(servers)} servers")
@bot.hybrid_command()
async def cs_mark_uninvitable(
ctx: commands.Context,
bot_id: int,
reason: str
):
"""Marks a bot as uninvitable in the cache server"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.csbots")):
return await ctx.send("You need ``borealis.csbots`` permission to use this command!")
# Check if a cache server
is_cache_server = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(ctx.guild.id))
if not is_cache_server:
return await ctx.send("This server is not a cache server")
# Check if bot is in cache_server_bots
count = await bot.pool.fetchval("SELECT COUNT(*) from cache_server_bots WHERE guild_id = $1 AND bot_id = $2", str(ctx.guild.id), str(bot_id))
if not count:
return await ctx.send("Bot is not in cache server")
await bot.pool.execute("UPDATE bots SET cache_server_uninvitable = $1 WHERE bot_id = $2", reason, str(bot_id))
await bot.pool.execute("DELETE FROM cache_server_bots WHERE bot_id = $1", str(bot_id))
await ctx.send("Bot marked as uninvitable")
@bot.hybrid_command()
async def cs_unmark_uninvitable(
ctx: commands.Context,
bot_id: int
):
"""Unmarks a bot as uninvitable"""
usp = await get_user_staff_perms(bot.pool, ctx.author.id)
resolved = usp.resolve()
if not has_perm(resolved, Permission.from_str("borealis.csbots")):
return await ctx.send("You need ``borealis.csbots`` permission to use this command!")
# Check if a cache server
is_cache_server = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(ctx.guild.id))
if not is_cache_server:
return await ctx.send("This server is not a cache server")
await bot.pool.execute("UPDATE bots SET cache_server_uninvitable = NULL WHERE bot_id = $1", str(bot_id))
await ctx.send("Bot unmarked as uninvitable")
@bot.hybrid_command()
async def cs_list_uninvitable(
ctx: commands.Context,
only_show_for_guild: bool = False
):
"""Shows a list of all bots marked as uninvitable with their reason"""
if only_show_for_guild:
is_cache_server = await bot.pool.fetchval("SELECT COUNT(*) from cache_servers WHERE guild_id = $1", str(ctx.guild.id))
if not is_cache_server:
return await ctx.send("This server is not a cache server")
bots = await bot.pool.fetch("SELECT bot_id, cache_server_uninvitable from bots WHERE guild_id = $1 AND cache_server_uninvitable IS NOT NULL", str(ctx.guild.id))
message = "Uninvitable bots for this server:\n"
for b in bots:
name = await bot.pool.fetchval("SELECT username from internal_user_cache__discord WHERE id = $1", b["bot_id"])
cache_server = await bot.pool.fetchrow("SELECT guild_id, invite_code, name from cache_servers WHERE guild_id = $1", str(ctx.guild.id))
message += f"\n- {name} [{b['bot_id']}]: {b['cache_server_uninvitable']} [{cache_server['guild_id']}, {cache_server['name']}, {cache_server['invite_code']}]"
if len(message) >= 1500:
await ctx.send(message)
message = ""