-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
2759 lines (2166 loc) · 100 KB
/
app.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 pathlib
import sys
import io
import os
import textwrap
import asyncio
import datetime
import hashlib
import time
from http import HTTPStatus
from typing import Any, Union
import enum
import secrets
import string
import math
import uuid
from base64 import urlsafe_b64encode
import asyncpg
import discord
import orjson
import requests
from dateutil import parser
from pydantic import BaseModel
import enums
import aiohttp
from redis import asyncio as aioredis
import orjson
from discord import Embed
from fastapi import FastAPI, WebSocket, HTTPException, Request, Response, APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.responses import StreamingResponse, ORJSONResponse, PlainTextResponse
from fastapi.exceptions import HTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from jinja2 import Environment, FileSystemLoader, select_autoescape
from colour import Color
from PIL import Image, ImageDraw, ImageFont
import staffapps
from experiments import Experiments, exp_props
import jwt
import pyotp
from xkcdpass import xkcd_password as xp
#import psycopg
debug = False
limited_view = ["reviews", "review_votes", "bot_packs", "vanity", "leave_of_absence", "user_vote_table",
"lynx_surveys", "lynx_survey_responses"]
class SPLDEvent(enum.Enum):
maint = "M"
refresh_needed = "RN"
missing_perms = "MP"
out_of_date = "OD"
unsupported = "U"
verify_needed = "VN"
ping = "P"
telemetry = "T"
not_found = "NF"
def to_type(value: Any, t: str, arr: bool):
if not t:
raise Exception("Could not find column, is it secret?")
t = t.lower()
if arr:
if not isinstance(value, list):
raise Exception("Value not a list")
value_encoded = []
for val in value:
print(val)
if not value:
continue # Ignore if not integer
value_encoded.append(to_type(val, t, False))
elif t in ("json", "jsonb"):
value_encoded = orjson.dumps(orjson.loads(value)).decode()
elif t.startswith("int") or t in ("bigint", "smallint", "serial", "bigserial"):
if not value.isdigit():
raise Exception("Value not a integer")
value_encoded = int(value)
elif t.startswith("float") or t in ("real", "double precision", "numeric", "money"):
if not value.replace(".", "").isdigit():
raise Exception("Value not a float")
value_encoded = float(value)
elif t.startswith("bool"):
value_encoded = value in ("true", "t", "1", "yes", "y")
elif t == "uuid":
value_encoded = uuid.UUID(value)
elif t.startswith("timestamp"):
value_encoded = parser.parse(value)
else:
value_encoded = value
return value_encoded
async def fetch_user(user_id: int):
async with aiohttp.ClientSession() as sess:
async with sess.get(f"http://localhost:1234/getch/{user_id}") as resp:
if resp.status == 404:
return {
"id": "",
"username": "Unknown User",
"avatar": "https://cdn.discordapp.com/embed/avatars/0.png",
"disc": "0000"
}
return await resp.json()
async def send_message(msg: dict):
msg["channel_id"] = int(msg["channel_id"])
msg["embed"] = msg["embed"].to_dict()
if not msg.get("mention_roles"):
msg["mention_roles"] = []
async with aiohttp.ClientSession() as sess:
async with sess.post(f"http://localhost:1234/messages", json=msg) as res:
return res
# Experiment sanity check
exps_in_api = requests.get("https://fates-api.select-list.xyz/experiments").json()
exps_found = []
for user_exp in exps_in_api["user_experiments"]:
try:
e = Experiments(user_exp["value"])
except:
print(f"[Lynx] User experiment sanity check failure (not found in Lynx): {user_exp['name']} ({user_exp['value']})")
sys.exit(0)
exps_found.append(e)
for exp in list(Experiments):
if exp not in exps_found:
print(f"[Lynx] User experiment sanity check failure (not found in API): {exp.name} ({exp.value})")
sys.exit(0)
elif not exp_props.get(exp.name):
print(f"[Lynx] User experiment sanity check failure (not found in exp_props): {exp.name} ({exp.value})")
sys.exit(0)
# End of experiment sanity check
def get_token(length: int) -> str:
secure_str = ""
for _ in range(0, length):
secure_str += secrets.choice(string.ascii_letters + string.digits)
return secure_str
with open("/home/meow/FatesList/config/data/discord.json") as json:
json = orjson.loads(json.read())
bot_logs = json["channels"]["bot_logs"]
main_server = json["servers"]["main"]
staff_server = json["servers"]["staff"]
access_granted_role = json["roles"]["staff_server_access_granted_role"]
bot_developer = json["roles"]["bot_dev_role"]
certified_developer = json["roles"]["certified_dev_role"]
certified_bot = json["roles"]["certified_bots_role"]
with open("/home/meow/FatesList/config/data/secrets.json") as json:
file = json.read()
file = orjson.loads(file)
main_bot_token = file["token_main"]
metro_key = file["metro_key"]
supabase_token = file["supabase_token"]
supabase_jwt_key = file["supabase_jwt_key"]
with open("/home/meow/FatesList/config/data/staff_roles.json") as json:
staff_roles = orjson.loads(json.read())
async def add_role(server, member, role, reason):
print(f"[LYNX] AddRole: {role = }, {member = }, {server = }, {reason = }")
url = f"https://discord.com/api/v10/guilds/{server}/members/{member}/roles/{role}"
async with aiohttp.ClientSession() as sess:
async with sess.put(url, headers={
"Authorization": f"Bot {main_bot_token}",
"X-Audit-Log-Reason": f"[LYNX] {reason}"
}) as resp:
if resp.status == HTTPStatus.NO_CONTENT:
return None
return await resp.json()
async def del_role(server, member, role, reason):
print(f"[LYNX] RemoveRole: {role = }, {member = }, {server = }, {reason = }")
url = f"https://discord.com/api/v10/guilds/{server}/members/{member}/roles/{role}"
async with aiohttp.ClientSession() as sess:
async with sess.delete(url, headers={
"Authorization": f"Bot {main_bot_token}",
"X-Audit-Log-Reason": f"[LYNX] {reason}"
}) as resp:
if resp.status == HTTPStatus.NO_CONTENT:
return None
return await resp.json()
async def ban_user(server, member, reason):
url = f"https://discord.com/api/v10/guilds/{server}/bans/{member}"
async with aiohttp.ClientSession() as sess:
async with sess.put(url, headers={
"Authorization": f"Bot {main_bot_token}",
"X-Audit-Log-Reason": f"[LYNX] Bot Banned: {reason[:14] + '...'}"
}) as resp:
if resp.status == HTTPStatus.NO_CONTENT:
return None
return await resp.json()
async def unban_user(server, member, reason):
url = f"https://discord.com/api/v10/guilds/{server}/bans/{member}"
async with aiohttp.ClientSession() as sess:
async with sess.delete(url, headers={
"Authorization": f"Bot {main_bot_token}",
"X-Audit-Log-Reason": f"[LYNX] Bot Unbanned: {reason[:14] + '...'}"
}) as resp:
if resp.status == HTTPStatus.NO_CONTENT:
return None
return await resp.json()
def code_check(code: str, user_id: int):
expected = hashlib.sha3_384()
expected.update(
f"Baypaw/Flamepaw/Sunbeam/Lightleap::{user_id}+Mew".encode()
)
expected = expected.hexdigest()
if code != expected:
print(f"[LYNX] CodeCheckMismatch {expected = }, {code = }")
return False
return True
class Unknown:
username = "Unknown"
# Staff Permission Checks
class StaffMember(BaseModel):
"""Represents a staff member in Fates List"""
name: str
id: Union[str, int]
perm: int
staff_id: Union[str, int]
async def is_staff_unlocked(bot_id: int, user_id: int, redis: aioredis.Connection):
return await redis.exists(f"fl_staff_access-{user_id}:{bot_id}")
async def is_staff(user_id: int, base_perm: int) -> Union[bool, int, StaffMember]:
if user_id < 0:
staff_perm = None
else:
async with aiohttp.ClientSession() as sess:
async with sess.get(f"http://localhost:1234/perms/{user_id}") as res:
staff_perm = await res.json()
if not staff_perm:
staff_perm = {"fname": "Unknown", "id": "0", "staff_id": "0", "perm": 0}
sm = StaffMember(name=staff_perm["fname"], id=staff_perm["id"], staff_id=staff_perm["staff_id"],
perm=staff_perm["perm"]) # Initially
rc = sm.perm >= base_perm
return rc, sm.perm, sm
with open("api-docs/staff-guide.md") as f:
staff_guide_md = f.read()
class CustomHeaderMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
if request.url.path in ("/widgets", "/widgets"):
return RedirectResponse("/widgets/docs")
if request.method == "OPTIONS":
if request.headers.get("Origin", "").endswith("fateslist.xyz") or request.headers.get("Origin", "").endswith("selectthegang-fates-list-sunbeam-x5w7vwgvvh96j5-5000.githubpreview.dev"):
return PlainTextResponse("", headers={
"Access-Control-Allow-Origin": request.headers.get("Origin"),
"Access-Control-Allow-Headers": "Authorization, Content-Type, Frostpaw-ID, Frostpaw-MFA, BristlefrostXRootspringXShadowsight, X-Cloudflare-For, Alert-Law-Enforcement",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
"Access-Control-Max-Age": "600"
})
response = await call_next(request)
if request.headers.get("Origin", "").endswith("fateslist.xyz") or request.headers.get("Origin", "").endswith("selectthegang-fates-list-sunbeam-x5w7vwgvvh96j5-5000.githubpreview.dev"):
response.headers["Access-Control-Allow-Origin"] = request.headers.get("Origin")
response.headers["Access-Control-Max-Age"] = "600"
return response
async def server_error(request, exc):
return HTMLResponse(content="Error", status_code=exc.status_code)
app = FastAPI(
title="Lynx Widgets API",
description="This is the public widgets API for Fates List",
docs_url=None,
redoc_url="/widgets/docs",
openapi_url="/widgets/docs/openapi",
terms_of_service="https://fateslist.xyz/frostpaw/tos",
license_info={
"name": "MIT",
"url": "https://github.com/Fates-List/FatesList/blob/main/LICENSE",
},
default_response_class=ORJSONResponse,
)
private = APIRouter(include_in_schema=False)
public = APIRouter(include_in_schema=True)
class ActionWithReason(BaseModel):
bot_id: str
owners: list[dict] | None = None # This is filled in by action decorator
main_owner: int | None = None # This is filled in by action decorator
context: Any | None = None
reason: str
app.state.bot_actions = {}
def action(
name: str,
states: list[enums.BotState],
min_perm: int = 2,
action_log: enums.UserBotAction | None = None
):
async def state_check(bot_id: int):
bot_state = await app.state.db.fetchval("SELECT state FROM bots WHERE bot_id = $1", bot_id)
return (bot_state in states) or len(states) == 0
async def _core(ws: WebSocket, data: ActionWithReason):
if ws.state.member.perm < min_perm:
return {
"detail": f"PermError: {min_perm=}, {ws.state.member.perm=}"
}
if not data.bot_id.isdigit():
return {
"detail": "Bot ID is invalid"
}
data.bot_id = int(data.bot_id)
if not await state_check(data.bot_id):
return {
"detail": f"Bot state check error: {states=}"
}
data.owners = await app.state.db.fetch("SELECT owner, main FROM bot_owner WHERE bot_id = $1", data.bot_id)
for owner in data.owners:
if owner["main"]:
data.main_owner = owner["owner"]
break
def decorator(function):
async def wrapper(ws: WebSocket, data: ActionWithReason):
if _data := await _core(ws, data):
return _data # Already sent ws message, ignore
if len(data.reason) < 5:
return {
"detail": "Reason must be more than 5 characters"
}
ws.state.user_id = int(ws.state.user["id"])
res = await function(ws, data) # Fake Websocket as Request for now TODO: Make this not fake
err = res.get("err", False)
if action_log and not err:
await app.state.db.execute("INSERT INTO user_bot_logs (user_id, bot_id, action, context) VALUES ($1, $2, $3, $4)", ws.state.user_id, data.bot_id, action_log.value, data.reason)
res = jsonable_encoder(res)
res["resp"] = "bot_action"
return res
app.state.bot_actions[name] = wrapper
return wrapper
return decorator
@action("claim", [enums.BotState.pending], action_log=enums.UserBotAction.claim)
async def claim(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3",
enums.BotState.under_review, request.state.user_id, int(data.bot_id))
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Claimed",
description=f"<@{request.state.user_id}> has claimed <@{data.bot_id}> and this bot is now under review.\n**If all goes well, this bot should be approved (or denied) soon!**\n\nThank you for using Fates List :heart:",
)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully claimed bot!", "ok": True}
@action("unclaim", [enums.BotState.under_review], action_log=enums.UserBotAction.unclaim)
async def unclaim(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1 WHERE bot_id = $2", enums.BotState.pending, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Unclaimed",
description=f"<@{request.state.user_id}> has stopped testing <@{data.bot_id}> for now and this bot is now pending review from another bot reviewer.\n**This is perfectly normal. All bot reviewers need breaks too! If all goes well, this bot should be approved (or denied) soon!**\n\nThank you for using Fates List :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully unclaimed bot", "ok": True}
@action("approve", [enums.BotState.under_review], action_log=enums.UserBotAction.approve)
async def approve(request: Request, data: ActionWithReason):
# Get approximate guild count
async with aiohttp.ClientSession() as sess:
async with sess.get(f"https://japi.rest/discord/v1/application/{data.bot_id}") as resp:
if resp.status != 200:
return ORJSONResponse({
"detail": f"Bot does not exist or japi.rest is down. Got status code {resp.status}"
}, status_code=400)
japi = await resp.json()
approx_guild_count = japi["data"]["bot"]["approximate_guild_count"]
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2, guild_count = $3 WHERE bot_id = $4",
enums.BotState.approved, request.state.user_id, approx_guild_count, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Approved!",
description=f"<@{request.state.user_id}> has approved <@{data.bot_id}>\nCongratulations on your accompishment and thank you for using Fates List :heart:",
)
embed.add_field(name="Reason", value=data.reason)
embed.add_field(name="Guild Count (approx)", value=str(approx_guild_count))
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
for owner in data.owners:
asyncio.create_task(add_role(main_server, owner["owner"], bot_developer, "Bot Approved"))
return {"detail": "Successfully approved bot", "guild_id": str(main_server), "bot_id": str(data.bot_id), "ok": True}
@action("deny", [enums.BotState.under_review], action_log=enums.UserBotAction.deny)
async def deny(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.denied,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Denied",
description=f"<@{request.state.user_id}> has denied <@{data.bot_id}>!\n**Once you've fixed what we've asked you to fix, please resubmit your bot by going to `Bot Settings`.**\n\nThank you for using Fates List :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully denied bot", "ok": True}
@action("ban", [enums.BotState.approved], min_perm=4, action_log=enums.UserBotAction.ban)
async def ban(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.banned,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Banned",
description=f"<@{request.state.user_id}> has banned <@{data.bot_id}>!\n**Once you've fixed what we've need you to fix, please appeal your ban by going to `Bot Settings`.**\n\nThank you for using Fates List :heart:",
)
embed.add_field(name="Reason", value=data.reason)
asyncio.create_task(ban_user(main_server, data.bot_id, data.reason))
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully banned bot", "ok": True}
@action("unban", [enums.BotState.banned], min_perm=4, action_log=enums.UserBotAction.unban)
async def unban(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.approved,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Unbanned",
description=f"<@{request.state.user_id}> has unbanned <@{data.bot_id}>!\n\nThank you for using Fates List again and sorry for any inconveniences caused! :heart:",
)
embed.add_field(name="Reason", value=data.reason)
asyncio.create_task(unban_user(main_server, data.bot_id, data.reason))
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully unbanned bot", "ok": True}
@action("certify", [enums.BotState.approved], min_perm=5, action_log=enums.UserBotAction.certify)
async def certify(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.certified,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Certified",
description=f"<@{request.state.user_id}> has certified <@{data.bot_id}>.\n**Good Job!!!**\n\nThank you for using Fates List :heart:",
)
embed.add_field(name="Feedback", value=data.reason)
for owner in data.owners:
asyncio.create_task(
add_role(main_server, owner["owner"], certified_developer, "Bot certified - owner gets role"))
# Add certified bot role to bot
asyncio.create_task(add_role(main_server, data.bot_id, certified_bot, "Bot certified - add bots role"))
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully certified bot", "ok": True}
@action("uncertify", [enums.BotState.certified], min_perm=5, action_log=enums.UserBotAction.uncertify)
async def uncertify(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1 WHERE bot_id = $2", enums.BotState.approved, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Uncertified",
description=f"<@{request.state.user_id}> has uncertified <@{data.bot_id}>.\n\nThank you for using Fates List but this was a necessary action :heart:",
)
embed.add_field(name="Reason", value=data.reason)
for owner in data.owners:
asyncio.create_task(
del_role(main_server, owner["owner"], certified_developer, "Bot uncertified - Owner gets role"))
# Add certified bot role to bot
asyncio.create_task(del_role(main_server, data.bot_id, certified_bot, "Bot uncertified - Bots Role"))
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully uncertified bot", "ok": True}
@action("unverify", [enums.BotState.approved], min_perm=3, action_log=enums.UserBotAction.unverify)
async def unverify(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.pending,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Unverified",
description=f"<@{request.state.user_id}> has unverified <@{data.bot_id}> due to some issues we are looking into!\n\nThank you for using Fates List and we thank you for your patience :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully unverified bot", "ok": True}
@action("requeue", [enums.BotState.banned, enums.BotState.denied], min_perm=3, action_log=enums.UserBotAction.requeue)
async def requeue(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET state = $1, verifier = $2 WHERE bot_id = $3", enums.BotState.pending,
request.state.user_id, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0x00ff00,
title="Bot Requeued",
description=f"<@{request.state.user_id}> has requeued <@{data.bot_id}> for re-review!\n\nThank you for using Fates List and we thank you for your patience :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully requeued bot", "ok": True}
@action("reset-votes", [], min_perm=3)
async def reset_votes(request: Request, data: ActionWithReason):
await app.state.db.execute("UPDATE bots SET votes = 0 WHERE bot_id = $1", data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Votes Reset",
description=f"<@{request.state.user_id}> has force resetted <@{data.bot_id}> votes due to abuse!\n\nThank you for using Fates List and we are sorry for any inconveniences caused :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully reset bot votes", "ok": True}
@action("reset-all-votes", [], min_perm=5)
async def reset_all_votes(request: Request, data: ActionWithReason):
if data.reason == "STUB_REASON":
data.reason = "Monthly Vote Reset"
async with app.state.db.acquire() as conn:
top_voted = await conn.fetch("SELECT bot_id, username_cached, votes, total_votes FROM bots WHERE state = 0 OR "
"state = 6 ORDER BY votes DESC, total_votes DESC LIMIT 7")
async with conn.transaction():
bots = await app.state.db.fetch("SELECT bot_id, votes FROM bots")
for bot in bots:
await conn.execute("INSERT INTO bot_stats_votes_pm (bot_id, epoch, votes) VALUES ($1, $2, $3)",
bot["bot_id"], time.time(), bot["votes"])
await conn.execute("UPDATE bots SET votes = 0")
await conn.execute("DELETE FROM user_vote_table")
embed = Embed(
url="https://fateslist.xyz",
title="All Bot Votes Reset",
color=0x00ff00,
description=f"<@{request.state.user_id}> has resetted all votes!\n\nThank you for using Fates List :heart:",
)
embed.add_field(name="Reason", value=data.reason)
top_voted_str = ""
i = 1
for bot in top_voted:
add = f"**#{i}.** [{bot['username_cached'] or 'Uncached User'}](https://fateslist.xyz/bot/{bot['bot_id']}) - {bot['votes']} votes this month and {bot['total_votes']} total votes. GG!\n"
if len(top_voted_str) + len(add) > 2048:
break
else:
top_voted_str += add
i += 1
embed.add_field(name="Top Voted", value=top_voted_str)
await send_message({"content": "", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully reset all bot votes", "ok": True}
@action("set-flag", [], min_perm=3)
async def set_flag(request: Request, data: ActionWithReason):
try:
data.context = int(data.context)
except ValueError:
return {"detail": "Flag must be an integer", "err": True}
try:
flag = enums.BotFlag(data.context)
except:
return {"detail": "Flag must be of enum Flag", "err": True}
existing_flags = await app.state.db.fetchval("SELECT flags FROM bots WHERE bot_id = $1", data.bot_id)
existing_flags = existing_flags or []
existing_flags = set(existing_flags)
existing_flags.add(int(flag))
try:
existing_flags.remove(int(enums.BotFlag.unlocked))
except:
pass
existing_flags = list(existing_flags)
existing_flags.sort()
await app.state.db.fetchval("UPDATE bots SET flags = $1 WHERE bot_id = $2", existing_flags, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Flag Updated",
description=f"<@{request.state.user_id}> has modified the flags of <@{data.bot_id}> with addition of {flag.name} ({flag.value})!\n\nThank you for using Fates List and we are sorry for any inconveniences caused :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully set flag", "ok": True}
@action("unset-flag", [], min_perm=3)
async def unset_flag(request: Request, data: ActionWithReason):
if not isinstance(data.context, int):
return {"detail": "Flag must be an integer", "err": True}
try:
flag = enums.BotFlag(data.context)
except:
return {"detail": "Flag must be of enum Flag", "err": True}
existing_flags = await app.state.db.fetchval("SELECT flags FROM bots WHERE bot_id = $1", data.bot_id)
existing_flags = existing_flags or []
existing_flags = set(existing_flags)
try:
existing_flags.remove(int(flag))
except:
return {"detail": "Flag not on this bot", "err": True}
try:
existing_flags.remove(int(enums.BotFlag.unlocked))
except:
pass
existing_flags = list(existing_flags)
existing_flags.sort()
await app.state.db.fetchval("UPDATE bots SET flags = $1 WHERE bot_id = $2", existing_flags, data.bot_id)
embed = Embed(
url=f"https://fateslist.xyz/bot/{data.bot_id}",
color=0xe74c3c,
title="Bot Flag Updated",
description=f"<@{request.state.user_id}> has modified the flags of <@{data.bot_id}> with removal of {flag.name} ({flag.value})!\n\nThank you for using Fates List and we are sorry for any inconveniences caused :heart:",
)
embed.add_field(name="Reason", value=data.reason)
await send_message({"content": f"<@{data.main_owner}>", "embed": embed, "channel_id": bot_logs})
return {"detail": "Successfully unset flag", "ok": True}
ws_action_dict = {
}
def ws_action(name: str):
def decorator(func):
ws_action_dict[name] = func
return func
return decorator
# Checks which approved and denied bots are on the site but not on support server
@ws_action("ss_check")
async def ss_check(websocket: WebSocket, _: dict):
exc_bots = [536991182035746816]
bots = await app.state.db.fetch("SELECT bot_id FROM bots WHERE state = $1 OR state = $2", enums.BotState.approved, enums.BotState.certified)
count = await app.state.db.fetchval("SELECT COUNT(1) FROM bots")
in_ss = 0
error_bots = []
for bot in bots:
if bot["bot_id"] in exc_bots:
continue
guild = app.state.discord.get_guild(int(main_server))
member = guild.get_member(bot["bot_id"])
if member:
in_ss += 1
else:
error_bots.append(str(bot["bot_id"]) + ": " + f"https://discord.com/api/oauth2/authorize?client_id={bot['bot_id']}&permissions=0&scope=bot%20applications.commands")
return {
"resp": "ss_check",
"total_count": count,
"approved_count": len(bots),
"in_ss": in_ss + len(exc_bots),
"error_bots": error_bots,
}
@ws_action("exp_rollout_menu")
async def exp_rollout_menu(ws: WebSocket, _: dict):
# Possible remove on experiment over
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 5:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
exp_initial = """
| Name | Value | Count | Users |
| :--- | :--- | :-- | :-- |
"""
exp_details = ""
for exp in list(Experiments):
exp_prop = exp_props.get(exp.name)
if exp_prop:
exp_details += f"""
#### {exp.name}
- Description: **{exp_prop.description}**
- Status: **{exp_prop.status.name} ({exp_prop.status.value})**
- Minimum Perm Filter (does not apply to full/controlled rollouts): **{exp_prop.min_perm}**
- Rollout Allowed (only applies to mass/controlled roll outs): **{exp_prop.rollout_allowed}**
"""
users = await app.state.db.fetch("SELECT user_id FROM users WHERE experiments && $1", [exp.value])
user_txt = "User count too low/high to display or rollout already complete"
if len(users) < 7 and len(users) > 0:
user_txt = []
for user in users:
user_txt.append(str(user["user_id"]))
user_txt = ", ".join(user_txt)
exp_initial += f"{exp.name} | {exp.value} | {len(users)} | {user_txt} |\n"
return {
"resp": "index",
"title": "Experiment Rollout",
"data": f"""
## Overview
{exp_initial}
## Experiments
{exp_details}
## Add User To Experiment
<div class="form-group">
<label for="exp_add-value">Experiment Value</label>
<input type="number" class="form-control" id="exp_add-value" placeholder="Experiment Value">
<label for="exp_add-id">User ID</label>
<input type="number" class="form-control" id="exp_add-id" placeholder="User ID">
<button onclick="addUserToExp()">Add</button>
</div>
## Remove User From Experiment
<div class="form-group">
<label for="exp_del-value">Experiment Value</label>
<input type="number" class="form-control" id="exp_del-value" placeholder="Experiment Value">
<label for="exp_del-id">User ID</label>
<input type="number" class="form-control" id="exp_del-id" placeholder="User ID">
<button onclick="delUserFromExp()">Remove</button>
</div>
## Controlled Rollout Experiment
<div class="form-group">
<label for="exp_rollout_controlled-value">Experiment Value</label>
<input type="number" class="form-control" id="exp_rollout_controlled-value" placeholder="Experiment Value">
<label for="exp_rollout_controlled-limit">Rollout Limit (suffix with % for percentage)</label>
<input type="text" class="form-control" id="exp_rollout_controlled-limit" placeholder="Experiment Limit">
<button onclick="rolloutControlled()">Rollout</button>
</div>
## Rollout Experiment
<div class="form-group">
<label for="exp_rollout-value">Experiment Value</label>
<input type="number" class="form-control" id="exp_rollout-value" placeholder="Experiment Value">
<button onclick="rolloutExp()">Rollout</button>
</div>
## Undo Rollout Experiment
<div class="form-group">
<label for="exp_rollout_undo-value">Experiment Value</label>
<input type="number" class="form-control" id="exp_rollout_undo-value" placeholder="Experiment Value">
<button onclick="rolloutExpUndo()">Undo</button>
</div>
""",
"ext_script": "exp-rollout"
}
@ws_action("exp_rollout_add")
async def exp_rollout_add(ws: WebSocket, data: dict):
# Possible remove on experiment over
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 5:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
try:
exp = Experiments(int(data["exp"]))
exp_prop = exp_props[exp.name]
if exp_prop.min_perm > 0:
# Check permission of new user
_, _, sm = await is_staff(int(data["id"]), 1)
if sm.perm < exp_prop.min_perm:
return {"detail": "Invalid user perm of new user"}
# remove old and add
await app.state.db.execute("UPDATE users SET experiments = array_remove(experiments, $1) WHERE user_id = $2", int(data["exp"]), int(data["id"]))
await app.state.db.execute("UPDATE users SET experiments = array_append(experiments, $1) WHERE user_id = $2", int(data["exp"]), int(data["id"]))
except:
return {"detail": "Invalid experiment data"}
return {"detail": "Added"}
@ws_action("exp_rollout_del")
async def exp_rollout_add(ws: WebSocket, data: dict):
# Possible remove on experiment over
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 5:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
try:
await app.state.db.execute("UPDATE users SET experiments = array_remove(experiments, $1) WHERE user_id = $2", int(data["exp"]), int(data["id"]))
except:
return {"detail": "Invalid experiment data"}
return {"detail": "Removed"}
@ws_action("exp_rollout_all")
async def exp_rollout_all(ws: WebSocket, data: dict):
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 7:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
try:
exp = Experiments(int(data["exp"]))
exp_prop = exp_props[exp.name]
if not exp_prop.rollout_allowed:
return {"detail": "Rollout not allowed for this experiment"}
except:
return {"detail": "Invalid experiment data"}
await app.state.db.execute("UPDATE lynx_data SET default_user_experiments = array_remove(default_user_experiments, $1)", int(data["exp"]))
await app.state.db.execute("UPDATE lynx_data SET default_user_experiments = array_append(default_user_experiments, $1)", int(data["exp"]))
await app.state.db.execute("UPDATE users SET experiments = array_remove(experiments, $1)", int(data["exp"]))
return {"detail": "Rolled out"}
@ws_action("exp_rollout_undo")
async def exp_rollout_all(ws: WebSocket, data: dict):
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 7:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
await app.state.db.execute("UPDATE users SET experiments = array_remove(experiments, $1)", int(data["exp"]))
await app.state.db.execute("UPDATE lynx_data SET default_user_experiments = array_remove(default_user_experiments, $1)", int(data["exp"]))
return {"detail": "Rolled out undone"}
@ws_action("exp_rollout_controlled")
async def exp_rollout_all(ws: WebSocket, data: dict):
if Experiments.LynxExperimentRolloutView not in ws.state.experiments:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
if ws.state.member.perm < 7:
return {"resp": "spld", "e": SPLDEvent.missing_perms}
elif not ws.state.verified:
return {"resp": "spld", "e": SPLDEvent.verify_needed}
try:
exp = Experiments(int(data["exp"]))
exp_prop = exp_props[exp.name]
if not exp_prop.rollout_allowed:
return {"detail": "Rollout not allowed for this experiment"}
except:
return {"detail": "Invalid experiment data"}
# Check percent prefix
try:
if data["limit"].endswith("%"):
user_count = await app.state.db.fetchval("SELECT COUNT(1) FROM users")
data["limit"] = math.ceil((float(data["limit"][:-1]) / 100) * user_count)
except:
return {"detail": "Invalid limit data"}
users = await app.state.db.fetch("SELECT user_id, experiments FROM users WHERE NOT (experiments && $1) ORDER BY RANDOM() LIMIT $2", [int(data["exp"])], int(data["limit"]))
for fetch in users:
await app.state.db.execute("UPDATE users SET experiments = array_append(experiments, $1) WHERE user_id = $2", int(data["exp"]), fetch["user_id"])
return {"detail": f"Pushed controlled roll out to {data['limit']} users"}
@ws_action("user_actions")
async def user_actions(ws: WebSocket, data: dict):
data = data.get("data", {})
# Easiest way to block cross origin is to just use a hidden input
if ws.state.member.perm < 2: