-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbb.py
2700 lines (2464 loc) · 120 KB
/
bb.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
# The Basement Bot
# Documentation: https://discordpy.readthedocs.io/en/latest/api.html
# Event reference: https://discordpy.readthedocs.io/en/latest/api.html?highlight=role%20mention#event-reference
from timeit import default_timer as dt
st=dt() # start of all code
# makes startup prettier. dont worry about it this totally doesnt hinder startup performance.
print()
#import warnings
#warnings.filterwarnings("ignore")
# discord-oriented tools
import discord
from discord.ext import commands
import json
import asyncio as aio
from discord_slash import SlashContext, SlashCommand
from discord_slash.utils.manage_commands import create_option, create_choice, create_permission
# system
import sys
from os.path import isfile, dirname, getsize, getmtime
from contextlib import redirect_stdout
from dotenv import dotenv_values as dev
import os
import psutil
import threading
from traceback import print_exc
# time
from datetime import datetime as datet, timedelta
from pytz import timezone
import time
# misc.
import random as rand
from hashlib import sha256 as sha
from io import StringIO
import http.server as httpserver
import openai
#from profanity_filter import ProfanityFilter
#from profanity_check import predict as pf_predict
# add something about pip install discord.py[voice]
BOOT_TIME=datet.now().strftime("%m/%d/%Y %H:%M:%S")
# initialize discord API
client=commands.Bot(
command_prefix="",
intents=discord.Intents.all(),
max_messages=1024,
owner_id=483000308876967937 # Me
)
slash=SlashCommand(client, sync_commands=True)
token=dict(dev(".env"))["bottoken"]
openai.api_key=dict(dev(".env"))["OPENAI_API_KEY"]
NUKE_PASS=dict(dev(".env"))["nukePass"]
MONTHS={
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'November',
12:'December'
}
# profanity library init
#profanity_filter=ProfanityFilter()
#profanity_filter.censor_char="."
# current directory
client.dir=dirname(__file__)
GUILDS=[858065227722522644]
STAFF_ID=936734394591363182
DEPRECATED=[
"setraw",
"jd",
"log",
"test",
"retrieve",
"announce",
"poll",
"create",
"stats",
"snow",
"msgs",
"del",
"warn",
"recent",
"count",
"dm",
"sha"
]
ALIASES=DEPRECATED+[
"clear",
"snowflake",
"statistics",
"hash"
]
# user defined functions
def create(data:dict[int,dict[str,]], id_:int, name:str, time:str): # creates a member in the member data dictionary
if id_ in data:
return
data[id_]={
"name":f"{name}",
"isMuted":False,
"warnCount":0,
"muteCount":0,
"banCount":0,
"msgCount":0,
"permLvl":0,
"countHigh":0,
"countFails":0,
"joinDate":time,
"birthday":"",
"history":[]
}
def save(dictionary): # saves member data in dictionary to hard storage
direct=dirname(__file__)
with open(f"{direct}/bb.json", "w") as f: json.dump(dictionary, f)
def load(): # loads member data
with open(f"{client.dir}/bb.json", "r") as f: r=json.loads(f.read())
new={int(i):r[i] for i in r if i.isdigit()}
for i in r:
if not i.isdigit(): new[i]=r[i]
return new
def isListed(m,list_): return m.author in list_
def toDigits(num:str) -> list[int]:
"""
Return a list of base-36 minus 10 converted string.
For #alphabet-counting
"""
return [-1]+[int(i,36)-10 for i in num]
def isNext(current:str,nextNum:str) -> bool:
current, nextNum = current.lower(), nextNum.lower()
if current==nextNum=="a":
return True
elif current[-1]=="z" and nextNum[-1]=="a":
digcurrent, dignextNum=toDigits(current),toDigits(nextNum)
return digcurrent[:-2]==dignextNum[:-2] and digcurrent[-2]+1==dignextNum[-2] or (current=="z"*len(current) and nextNum=="a"*len(nextNum) and len(current)==len(nextNum)-1)
elif len(current)==len(nextNum):
digcurrent, dignextNum=toDigits(current),toDigits(nextNum)
return digcurrent[:-1]==dignextNum[:-1] and digcurrent[-1]+1==dignextNum[-1]
else:
return False
async def nickToMember(nick:str,author:discord.Member,ctx:SlashContext):
memberGuesses:list[discord.Member]=[kiddie for kiddie in client.basement.members if kiddie.display_name.startswith(nick) or kiddie.name.startswith(nick)]
if len(memberGuesses)==1:
return memberGuesses[0]
else:
glist="\n"+"\n".join(kiddie.display_name for kiddie in memberGuesses)
await ctx.send(f"{author.mention}, there are `{len(memberGuesses)}` people that match the username you provided me with (\"{nick}\") please check your spelling and/or specify further.{glist}")
return
def nickToMemberSync(nick:str)->list[discord.Member]:
return [kiddie for kiddie in client.basement.members if kiddie.display_name.startswith(nick) or kiddie.name.startswith(nick)]
def verify(i:str)->bool: return i.strip() and not i.strip().startswith("#") and len(i.strip())-1
def getPermissions()->dict[str,str]:
with open(f"{client.dir}/bb.py",'r') as f: fread=[i.strip() for i in f.read().split("class slashCmds:")[-1].split('\n')]
return {l[len("async def _"):].split("(")[0]:fread[i+1][1] for i,l in enumerate(fread) if l.startswith("async def _") and fread[i+1][1] in ["a","s","e"]}
def checkPermission(cmdPerm:str,memberPerm:str)->bool:
translation={
"a":2,
"s":1,
"e":0
}
return translation[cmdPerm]<=translation[memberPerm]
def parseDesciptions(cmd:str=None,maxPerm:str="e")->dict:
"this was a ***** to code"
print(maxPerm)
# convert non-listed cmd to all cmds
permissions=getPermissions()
if not cmd: cmds=["/"+cmd[1:] for cmd in dir(slashCmds) if not cmd.startswith("__") and checkPermission(permissions[cmd[1:]],maxPerm)]
else: cmds=[cmd]
out={}
# grabs file from "class slashCmds:" down as list `fread`, no whitespaces
with open(f"{client.dir}/bb.py",'r') as f: fread=[i.strip() for i in f.read().split("class slashCmds:")[-1].split('\n') if verify(i)]
for command in cmds:
for idx,line in enumerate(fread):
if line.startswith("name=") and fread[idx-1]=="@slash.slash(" and line[6:-2]==command[1:]:
name=command[1:]
if fread[idx+1].startswith("description=f\""): desc=fread[idx+1][14:-2]
else: desc=fread[idx+1][13:-2]
out[name]=desc
return out
def convertAttr(attr:str)->str:
translations={
"name":"Name",
"isMuted":"Is muted?",
"warnCount":"Warn count",
"muteCount":"Mute count",
"banCount":"Ban count",
"msgCount":"Message count",
"permLvl":"Permission level",
"countHigh":"Highest count",
"countFails":"Count fails",
"joinDate":"Date joined",
"birthday":"Birthday"
}
return translations[attr] if attr in translations else "INTERNALERROR"
def scanMessage(phrase:str, string:str) -> bool:
phrase=phrase.lower()
string=string.lower()
chars=['"',"'",".",",","-","","*"]
try: percent=len([i for i in string if i==" "])/len(string)
except ZeroDivisionError: percent=1
for char in chars:
if string!="he'll" and phrase in string.replace(char,"").split(" "):# and not phrase in string:
return string.replace(char,"").replace(phrase, f"||{phrase}||")
if phrase in string.replace(" ","") and not phrase in string and percent>.42:
return string.replace(" ","").replace(phrase, f"||{phrase}||")
elif f" {phrase} " in string or phrase==string:
return string.replace(phrase, f"||{phrase}||")
else:
return False
def properOrdinal(number:str)->str:
if number.endswith("0") or number.endswith("4") or number.endswith("5") or number.endswith("6") or number.endswith("7") or number.endswith("8") or number.endswith("9"):
return number+"th"
elif number[1]=="1":
return number+"th"
elif number.endswith("1"):
return number+"st"
elif number.endswith("2"):
return number+"nd"
elif number.endswith("3"):
return number+"rd"
else: raise ValueError("AAAAAAAAAAAAAAAAAAAAAAAA")
def correctBday(bday:str)->str:
bday=bday.replace("/0","/")
return bday[1:] if bday.startswith("0") else bday
def properBday(bday:str)->str:
if bday.startswith("0") or "0/" in bday: bday=correctBday(bday)
month,day=bday.split("/")
return f"{MONTHS[int(month)]} {properOrdinal(day)}"
def removePunctuation(words:list[str])->list[str]:
out=[]
for word in words:
for i in (".","!","?","'",",",'"'):
if i in word: word=word.replace(i,"")
out.append(word)
return out
# Grab our json/dictionary
client.Data=load()
if client.Data:
print("[BasementBot] Client data read sucessfully!")
####################################################################################################
class Interbot (httpserver.BaseHTTPRequestHandler):
def end_headers(self):
#now=datet.now().strftime("%H:%M:%S")
#print(f"[Interbot] {now} - triggered end_headers()")
self.send_header("Access-Control-Allow-Origin","https://bot.thebasement.group")
super().end_headers()
# Silence requests log
def log_request(self, code="-", size="-"):
return
def do_OPTIONS(self):
if self.path=="/cmd":
self.send_response(200)
self.send_header("Access-Control-Allow-Headers","content-type, accepts")
self.send_header("Access-Control-Allow-Methods","POST,OPTIONS")
self.send_header("Content-type","text/plain")
self.send_header("allow","OPTIONS, POST")
self.end_headers()
else:
self.quick_code(404)
def do_GET(self):
try:
self.send_response(200)
self.send_header("Content-type","text/plain")
self.end_headers()
self.wfile.write("Hey there!\n".encode())
except:
print_exc()
def body(self)->dict[str,]:
return json.loads(self.rfile.read(int(self.headers.get("Content-Length"))))
def validate(self,password:str)->bool:
with open("/root/basementbot/passwords",'r') as f: return password in [i.strip() for i in f.readlines()]
# 2xx responses. adds headers and sends response
def _200(self,data:dict[str,]):
self.send_response(200)
self.send_header("Content-type","application/json")
self.end_headers()
self.wfile.write(json.dumps(data).encode())
# any HTTP response code. adds headers and sends response
def quick_code(self,code:int,message:str=None):
self.send_response(code)
if not message: self.end_headers()
else:
self.send_header("Content-type","application/json")
self.end_headers()
self.wfile.write(json.dumps({"msg":message}).encode())
def parse_args(self,arg:str):
"Auto converts a `;`-seperated string of keys into a list of integers and strings."
if type(arg)==str:
arg=arg.strip()
return int(arg) if arg.isdigit() else arg
return arg
def do_POST(self):
if not self.path in ("/test","/cmd"):
self.quick_code(404)
return
body=self.body()
try: isValid=self.validate(body["password"])
except: self.quick_code(400,"Expected: \"password\"")
else:
if isValid:
if self.path=="/test":
self.send_response_only(200,"all good!")
self._200({
"msg":"hi"
})
return
elif self.path=="/cmd":
# cmd can be a variety of commands
# dgn - diagnostics
# ret - gets the value of some item in the dictionary
# set - changes the value of some item in the dictionary
# tst - experimental
# bbt - execute slash commands
# res - will resolve discord IDs to json objects that note it's attributes
# lok - will lookup a member's nickname or username based on .startswith()
# rrc - reaction roles configuration
# qev - query events
# rmg - edit reaction role message in the reaction roles channel
if "command" in body:
command:str=body["command"]
if command=="dgn":
# args: None
# returns: a dict of current operating values
data={
"upt":BOOT_TIME,
"cpu":str(psutil.cpu_count()),
"cpr":str(psutil.cpu_percent()),
"ram":str(psutil.virtual_memory().available),
"rpr":str(psutil.virtual_memory().percent),
"pid":str(os.getpid())
}
self._200(data)
#print(f"[Interbot] i just sent {data}")
elif command=="set":
# args: path,value
# path: required. a list of keys
# value: required. a string of the new value of path
# returns: a confirmation, client.Data is modified
if not "path" in body:
self.quick_code(400,"Expected: \"path\"")
return
elif not "value" in body:
self.quick_code(400,"Expected: \"value\"")
return
path=body["path"]
value=self.parse_args(body["value"])
for place in path:
# will (hopefully) prevent rexec
if "]" in place or ";" in place: # set a,b,c target
# set a,b]; kmksdo[fmiko[g]] #
self.quick_code(418,"no")
return
if type(value)==str:
if ";" in value:
# will (hopefully) prevent rexec
self.quick_code(418,"no")
return
try:
execCommand="client.Data"+"".join(f"[\"{arg}\"]" if type(arg)==str else f"[{arg}]" for arg in path)
execCommand+="="+(f"\"{value}\"" if type(value)==str else str(value))
# this isn't dangerous at all
exec(execCommand)
target=client.Data
for place in path:
target=target[place]
if str(target)!=str(target).replace('"',"'"):
print(f"target: {target} - {type(target)}")
print(f"path: {path}")
print(f"command: {execCommand}")
raise ValueError
except ValueError:
print_exc()
self.quick_code(500,"Unsuccessfully set.")
return
except:
print_exc()
self.quick_code(500,"Internal error\nContact josh@thebasement.group")
return
"⍼"
else:
self._200({
"msg":"Success!"
})
return
elif command=="ret":
# args: path
# path: required. the path to the desired target
# returns: the bot's dictionary record at the target
if not "path" in body:
self.quick_code(400,"Expected: \"path\"")
return
path=body["path"]
target=client.Data
for place in path:
place=place.strip()
if place.isdigit(): place=int(place)
try:
target=target[place]
except KeyError:
self.quick_code(404,f"{place} not found")
return
else:
# Change all integer values in target to strings
if type(target)==dict:
for key,value in target.items():
if type(value)==int: target[key]=str(value)
self._200(target)
elif command=="res":
# args: id
# id: required. the id of the unknown object
# returns: a dictionary of a discord object
basem:discord.Guild=client.basement
converters=(basem.get_channel,basem.get_member,basem.get_role,client.get_emoji)
for converter in converters:
conv=converter(int(body["id"]))
try:
if conv is not None:
self._200(conv.__dict__())
return
except AttributeError:
print_exc()
self.quick_code(500,f"Error resolving {body['id']}")
else:
self.quick_code(404,"Could not resolve")
elif command=="lok":
# args: nick
# nick: a string representing the nickname
# returns: a member object
if not "nick" in body:
self.quick_code(400,f"Expected: \"nick\"")
return
nick:str=body["nick"]
self._200({
member.display_name:client.basement.get_member(member.id).__dict__() for member in nickToMemberSync(nick)
})
elif command=="rrc":
# args: roles
# roles: a dictionary of emoji to role names
# returns: a status message
if not "roles" in body:
self.quick_code(400,"Expected: \"roles\"")
return
roles:dict[str,str]=body["roles"]
newTable:dict[str,str]={}
for emoji,role in roles.items():
for gRole in client.basement.roles:
if gRole.name.lower().startswith(role.lower()):
newTable[emoji]=str(gRole.id)
break
else:
self.quick_code(404,f"Could not find role {role}")
return
client.Data["RR"]["table"]=newTable
async def _rrc():
messages:list[discord.Message]=await client.get_channel(client.Data["RR"]["channel"]).history(limit=1).flatten()
message=messages[0]
for reaction in message.reactions:
if reaction.emoji not in client.Data["RR"]["table"]:
print(f"Clearing {reaction.emoji} ...")
await reaction.clear()
aio.run_coroutine_threadsafe(_rrc(),client.loop)
self._200({
"msg":"Success"
})
elif command=="qev":
# args: event
pass
elif command=="rmg":
# args: none
# returns: a status message
try:
message="React with any of the emojis listed below to get a role! (and be honest, we know where you live)\n"
message+="\n".join(f" {emoji} - {client.basement.get_role(int(role)).mention}" for emoji,role in client.Data["RR"]["table"].items())
async def _rmg():
channel:discord.TextChannel=client.basement.get_channel(client.Data["RR"]["channel"])
lastmsg:list[discord.Message]=await channel.history(limit=1).flatten()
if lastmsg[0].author!=client.user:
await lastmsg[0].delete()
await channel.send(message)
else: await lastmsg[0].edit(content=message)
aio.run_coroutine_threadsafe(_rmg(),client.loop)
except:
now=datet.now().strftime("%m/%d/%Y %H:%M:%S")
print(f"{now} [Interbot] Error in rmg")
print_exc()
self.quick_code(500,"Internal error\nContact")
else:
self._200({
"msg":"Success"
})
else:
self.quick_code(404,f"Unknown command: \"{command}\"")
else:
self.quick_code(400,"Expected: \"command\"")
return
else:
self.quick_code(401,"Incorrect password")
return
####################################################################################################
@client.event
async def on_ready(): # do all this on startup...
st=dt()
client.basement=client.get_guild(858065227722522644) # basement guild
#client.botLog=client.basement.get_channel(862004853763866624) # bot log channel
#client.modLog=client.basement.get_channel(888981385585524766) # mod log channel
client.counting=client.basement.get_channel(903043416571662356) # counting channel
client.welcome=client.basement.get_channel(858065227722522647) # welcome channel
#client.checklist=client.basement.get_channel(862567884286984202)
client.rules=client.basement.get_channel(858156716238438421)
#client.group=client.basement.get_channel(871455541602430986) - channel deleted
client.faq=client.basement.get_channel(858200405933555722)
client.basementC=client.basement.get_channel(858157764530798612)
client.wRole=client.basement.get_role(908491255812616252) # welcome role
client.kRole=client.basement.get_role(858234453653848065) # kiddie role
client.modRole=client.basement.get_role(858416941185761290) # moderator role
client.adminRole=client.basement.get_role(858223675949842433) # admin role
client.breakbbC=client.basement.get_channel(910345635365015613) # break-basementbot channel
client.wrdAssocC=client.basement.get_channel(859807366219694080) # word association channel
client.lSSC=client.basement.get_channel(933183879983013968) # newest minigame, long-story-short
client.testC=client.basement.get_channel(933576021641400370) # test channel in dev category
client.alphaCountC=client.basement.get_channel(932125853003943956) # alphabet counting channel, minigame
client.announcementC=client.basement.get_channel(858156757788524554)
client.spamC=client.basement.get_channel(942576682395660358) # spam channel
client.botInteractC=client.basement.get_channel(858422701165510690) # bot-interactions channel
client.noahb=client.basement.get_member(806307221171994624) # noah
client.josh=client.basement.get_member(483000308876967937) # josh smith
client.modGenC=client.basement.get_channel(862035189159690280) # mod-general channel
client.staffRole=client.basement.get_role(936734394591363182) # staff role
client.alertC=client.basement.get_channel(960376643329851432) # bot alerts channel
client.disciplineC=client.basement.get_channel(973750522651766794) # discipline channel
client.deletedMessages=[] # for tracking which messages we've deleted
client.lastSave=dt() # used for autosaving
client.localTZ=timezone("US/Central")
print(f"Set up client variables in {dt()-st}s!")
# edit reconnect message, if it exists
try: recChannelID, recMsgID=client.Data["reconnect"]
except KeyError: pass
except Exception as e: print(f"{_dt} [BasementBot] There was an internal error during reconnect message edit.\n{repr(e)}")
else:
channel:discord.TextChannel=client.get_channel(recChannelID)
message:discord.PartialMessage=channel.get_partial_message(recMsgID)
try:
await message.edit(embed=discord.Embed(title="Reconnected!",color=discord.Color.green()))
except:
print("no reconnect message")
_dt=datet.now().strftime("%m/%d/%Y %H:%M:%S") # current time
# repair files
for channel in client.basement.channels:
if not isfile(f"{client.dir}/logs/{channel.id}.txt"):
with open(f"{client.dir}/logs/{channel.id}.txt", "w", encoding='utf-8') as f: print((f"BEGINNING OF #{channel.name}\n"), file=f) # if the channel log does not exist, create it
for kiddie in [member for member in client.basement.members if not member.bot]: # in the case that data was corrupted, repair kiddie files
kiddie:discord.Member
if kiddie.id not in client.Data:
create(client.Data, kiddie.id, kiddie.display_name, _dt)
for role in kiddie.roles: # determine permission level for every kiddie
if role.name=="Administrator":
client.Data[kiddie.id]["permLvl"]=2
break
elif role.name=="Moderator":
client.Data[kiddie.id]["permLvl"]=1
break
if kiddie.id==806307221171994624: client.Data[kiddie.id]["permLvl"]=3 # noah
elif "joinDate" not in client.Data[kiddie.id]:
print(f"[BasementBot] Created joinDate entry for \"{kiddie.display_name}\"")
joinDate:datet=kiddie.joined_at
client.Data[kiddie.id]["joinDate"]=joinDate.astimezone(client.localTZ).strftime("%m/%d/%Y %H:%M:%S")
# fix this later
#if client.adminRole not in kiddie.roles:
# for char in kiddie.display_name:
# if char.lower() not in [i for i in "abcdefghijklmnopqrstuvwxyz()!~0123456789[]<>{}-_+=*^%$#@&/\\|?.,;:'"]:
# try:
# await kiddie.send(f"Dear {kiddie.mention},\n\nI noticed you had special characters in your name, and this messes with my systems. Will you kindly change it to something without special characters while Josh tries to figure out a solution? If you didn't use a special character, please harrass MR_H3ADSH0T#0001 (Josh) until he fixes it lol\n\n\t\tSincerely, The Basement Staff Team")
# except:
# await client.botAlertsC.send(embed=discord.Embed(title="",description=f"{kiddie.mention} has special characters in their name, and I couldn't DM them to fix it. Please change their name to something without special characters.",color=discord.Color.red()))
# break
# status
notBots=[member for member in client.basement.members if not member.bot] # i don't know why, but the bot is always one less than the current count...
await client.change_presence(activity=discord.Streaming(name=f"we've got {len(notBots)} members!",url="https://thebasement.group"))
# sucess report
await client.alertC.send(embed=discord.Embed(title="Connected",description=f"Bot connected at `{_dt}`",color=discord.Color.green())) # report connection
hour, minute = client.Data["randTime"]
print(f"[BasementBot] Sucessfully loaded bot configurations! Startup took {dt()-st}s!\nGood-morning Time: {hour}:{minute}")
print(f"Boot time: {BOOT_TIME}")
# main loop
while True:
# dont DoS our bot, keep it slow but not too slow
await aio.sleep(1)
#if not server.isRunning:
# server.server_close()
# print("[Interbot] ok i shut down you dumb f***")
now=datet.now()
##################################
######### ROUTINE CASUAL #########
##################################
# handles good morning
if client.Data["GMday"]!=now.day and [now.hour,now.minute]==client.Data["randTime"]: # at a random time in the morning
await client.basementC.send(f"Good morning guys!")
client.Data["GMday"]=now.day # reset day
client.Data["randTime"]=[rand.randint(5,14),rand.randint(0,59)] # new random time
# handles happy birthday
if (now.hour,now.minute,now.second)==(9,0,0): # 9am
monthDay=now.strftime("%m/%d")
for member in [i for i in client.Data if type(i)==int]:
try:
if client.Data[member]["birthday"]==monthDay:
member:discord.Member=client.basement.get_member(member)
await client.basementC.send(embed=discord.Embed(title="HAPPY BIRTHDAY!",description=f"Wishing **{member.display_name}** a happy birthday! :tada:",color=member.color))
except KeyError:
await client.alertC.send(f"{client.josh.mention} i had an error finding {member.display_name}'s birthday data")
print(f"Coudn't find 'happy birthday' for {member} ({client.Data[member]['name']})")
# handles good night
if (now.hour,now.minute,now.second)==(23,59,59) and (now.month,now.day)!=(12,31): # will say "Goodnight, y'all" at 11:59:59pm EXCEPT on new year's
await client.basementC.send(f"Good night, y'all 😴")
##################################
####### ROUTINE MODERATION #######
##################################
# executes "/log" every hour
#if (now.minute,now.second)==(0,0):
# online,o,dt_str="",0,now.strftime("%m/%d/%Y %H:%M:%S")
# for kiddie in client.basement.members:
# if kiddie.raw_status!="offline" and kiddie.bot==False:
# online+=" - "+kiddie.display_name+"\n"
# o+=1
# await client.alertC.send(f"This was an auto-initiated process. Use `/log` to see this list.\n{o} online members at `{dt_str}`:```\n{online}```") # send to #modlogging
# await aio.sleep(10)
# handles bi-hourly saves
if now.second==0 and not now.minute%30: save(client.Data)
# handles spam purge
if (now.hour,now.minute,now.second)==(0,0,0):
deleteTime:datet=datet(
year=now.year,
month=now.month,
day=now.day,
hour=now.hour,
minute=now.minute,
second=now.second
) - timedelta(days=1)
spamC:discord.TextChannel=client.spamC
await spamC.purge(limit=8192,before=deleteTime)
#await client.modLog.send(f"```{_dt} purged #spam messages.```")
#################################
######## CALENDAR EVENTS ########
#################################
# handles happy new year
if (now.month,now.day,now.hour,now.minute)==(12,31,23,59):
if now.second==0:
await client.basementC.send("Get ready for the new year countdown!")
cd=""
if now.second>10:
cd=f"***{60-now.second}***"
else:
cd=f"{60-now.second}"
await client.basementC.send(cd)
# handles basement anniversary
if (now.month,now.day,now.hour,now.minute,now.second)==(6,25,19,24,52):
happyAnniv=discord.Embed(description=f"Happy Birthday, Basement! Here's to another year of awesomeness!\nOh, and the next time you see {client.noahb.mention}, tell him how much you like The Basement! (He'll blush haha)",color=discord.Color.purple())
happyAnniv.set_author(name="HAPPY BASEMENT ANNIVERSARY!!!",icon_url="https://test.thebasement.group/images/tada.png")
await client.basementC.send(embed=happyAnniv)
# handles valentine's day
if (now.month,now.day,now.hour,now.minute,now.second)==(2,14,12,1,0):
valintDay=discord.Embed(description="Have a great valintines day, whether you're a single pringle, or a hopeless romantic! Just know that someone out there loves you very very much ❤️",color=discord.Color.red())
valintDay.set_author(name="Happy Valentine's Day!",icon_url="https://test.thebasement.group/images/heart.png")
await client.basementC.send(embed=valintDay)
# handles 2/22/22 22:22:22
if (now.year-2000,now.month,now.day,now.hour,now.minute,now.second)==(22,2,22,22,22,22):
_dtstr=now.strftime("%m/%d/%Y %H:%M:%S")
await client.basementC.send(embed=discord.Embed(title="Happy twosday!",description=f"The time is:\n```{_dtstr} CST```"))
@client.event
async def on_member_join(member:discord.Member):
_dt=datet.now().strftime("%m/%d/%Y %H:%M:%S") # current time
if member.id!=864881059187130458 and member.id not in client.Data: # not Josh S. (alt)
await client.welcome.send(f"{client.wRole.mention}, give a warm welcome to our newest member, {member.display_name}!") # public welcome
elif member.id in client.Data:
await client.welcome.send(f"{member.display_name} has returned!")
if member.id==864881059187130458: # be funny bc alt
await client.welcome.send(f"Yo <@864881059187130458> is here. Josh must be testing stuff again :man_shrugging:")
# private DM
await member.send(f"Dear, {member.mention}, thank you for joining **{client.basement.name}**! Please read the {client.rules.mention} channel before exploring the server. Also, the Admin team loves to hear everyone's brilliant ideas, so using {client.faq.mention} is encouraged!\n\n Sincerely, the Admin team")
# give member childrne roll
await member.add_roles(client.kRole)
create(client.Data, member.id, member.display_name, _dt)
save(client.Data)
# update member count
notBots=[i for i in client.basement.members if not i.bot] # see on_ready()
await client.alertC.send(embed=discord.Embed(title="Member Joined",description=f"**{member.display_name}** just joined, bringing the member count to: `{len(notBots)}`",color=discord.Color.blue()))
await client.change_presence(activity=discord.Streaming(name=f"we've got {len(notBots)} members!",url="https://thebasement.group"))
@client.event
async def on_member_remove(member:discord.Member):
await client.welcome.send(f"{member.display_name} has left us... wishing them a happy life :)")
notBots=[i for i in client.basement.members if not i.bot] # see on_ready()
await client.alertC.send(embed=discord.Embed(title="Member Left",description=f"**{member.name}#{member.discriminator}** has left the server.\nThere are now {len(notBots)} members in the server.",color=discord.Color.black())) # had to modify the discord color file for this to work to work with the new embeds
await client.change_presence(activity=discord.Streaming(name=f"we've got {len(notBots)} members!",url="https://thebasement.group"))
@client.event
async def on_member_update(before:discord.Member, after:discord.Member):
now=datet.now()
_dt=now.strftime("%m/%d/%Y %H:%M:%S") # get current time/date
with open(f"{client.dir}/logs/nicknames.txt",'a', encoding="utf-8") as f:
if before.display_name!=after.display_name:
print(f"{_dt} {before.name} \"{before.display_name}\" -> \"{after.display_name}\"")
for word in client.Data["blw"]:
if scanMessage(word,after.display_name):
await after.edit(nick=before.display_name)
break
# fix this later
## check and prevent special chars in everyone but admins
#if client.adminRole not in before.roles:
# for char in after.display_name:
# if char.lower() not in [i for i in "abcdefghijklmnopqrstuvwxyz()!~0123456789[]<>{}-_+=*^%$#@&/\\|?.,;:'"]:
# await after.edit(nick=before.display_name)
# await after.send(f"Dear {after.mention},\n\nPlease don't use special characters in your nickname. If you didn't use a special character, please harrass MR_H3ADSH0T#0001 (Josh) until he fixes it lol\n\n\t\tSincerely, The Basement Staff Team")
# break
with open(f"{client.dir}/logs/master.txt", "a", encoding="utf-8") as f:
if before.status!=after.status and before.id!=691383407548301432: # change in status -- also dont include impersonator! creates clutter
print(f"{_dt} {before.name} ({before.display_name})'s status was changed from \"{before.status}\" to \"{after.status}\"!", file=f)
elif before.activity!=after.activity: # change in activity.... this is actually kinda creepy and a little bit intrusive
print(f"{_dt} {before.name} ({before.display_name})'s activity was changed from {before.activity} to {after.activity}!", file=f)
elif before.roles!=after.roles: # this is useful for identifying if that person was promoted or demoted
# find out which role was changed
bRoles,aRoles=[role.name for role in before.roles],[role.name for role in after.roles] # list of role names of before and after
if len(bRoles)>len(aRoles): # find out which role was removed
missing=str(list(set(bRoles)-set(aRoles))[0])
print(f"{_dt} {before.name} ({before.display_name}) lost the role {missing}!", file=f)
if missing in ["Admin","Mod"]: client.Data[before.id]["permLvl"]-=1 # if the role was important, subtract one... this is really quite clever actually
if len(bRoles)<len(aRoles): # find out which role was added
gained=str(list(set(aRoles)-set(bRoles))[0])
print(f"{_dt} {before.name} ({before.display_name}) recieved the role {gained}!", file=f)
if gained in ["Admin","Mod"]: client.Data[before.id]["permLvl"]+=1 # see line 113 comment
elif before.pending!=after.pending: # no use for verification right now...
print(f"{_dt} {before.name} ({before.display_name})'s verification was changed from {before.pending} to {after.pending}!", file=f)
@client.event
async def on_message_delete(message:discord.Message):
_dt=datet.now().strftime("%m/%d/%Y %H:%M:%S") # get current time/date
auth=message.author # author
if message.author.id==client.user.id or message.channel.category_id in (872720713742704671,858162628537745408): pass # dont log our own messages
if message.id in client.deletedMessages: # if the message was already deleted
client.deletedMessages.remove(message.id) # remove it from the list
return # do nothing
elif message.attachments and message.channel not in (client.counting, client.alphaCountC, client.alertC): # if there are attachments
for att in message.attachments:
content="!" if not message.content else f": \"{message.content}\"" # get content if there is any
await client.alertC.send(embed=discord.Embed(title="Message deleted!",description=f"**{auth.display_name}**'s message in {message.channel.mention} was deleted{content}\nURL: [{att.filename}]({att.proxy_url})",color=discord.Color.red()))
elif message.channel not in (client.counting, client.alphaCountC, client.alertC): # if there are no attachments
await client.alertC.send(embed=discord.Embed(title="Message deleted!",description=f"**{auth.display_name}**'s message in {message.channel.mention} was deleted: \"{message.content}\"",color=discord.Color.red()))
if message.channel.category_id not in (872720713742704671,858162628537745408):
with open(f"{client.dir}/logs/{message.channel.id}.txt", "a", encoding="utf-8") as f:
try:
print(f"{_dt} {auth.name} ({auth.display_name})'s message was deleted \"{message.clean_content}\" in {message.channel.name}", file=f)
except AttributeError:
print(f"{_dt} {auth.name} ({auth.display_name})'s message was deleted \"{message.clean_content}\" in (probably) the DMs", file=f)
if message.channel==client.counting and message.content.isdigit() and not message.content.startswith("0"): # counting alert
await client.counting.send(f"{auth.name}'s message \"`{message.clean_content}`\" was deleted! The current number is `{client.Data['counting']}`")
@client.event
async def on_message_edit(before:discord.Message,after:discord.Message):
_dt=datet.now().strftime("%m/%d/%Y %H:%M:%S") # get current time/date
auth=before.author # author
Bclean=before.clean_content # before
Aclean=after.clean_content # after
if before.author.id in (client.user.id, 282859044593598464): # dont log our own messages or ProBot's messages
pass
elif before.content!=after.content:
await client.alertC.send(embed=discord.Embed(title="Message edited!",description=f"**{auth.display_name}** edited their message in {before.channel.mention} from: \"{Bclean}\"\nTo: \"{Aclean}\"",color=discord.Color.orange()))
if after.content.replace(":","")=="420":
for reaction in after.reactions:
# check if thumbs up
if reaction.emoji=="\U0001f44d":
await reaction.clear()
with open(f"{client.dir}/logs/{before.channel.id}.txt", "a",encoding="utf-8") as f:
print(f"{_dt} {auth.name} ({auth.display_name}) changed their message from \"{Bclean}\" to \"{Aclean}\" (path: {before.channel.id}/{before.id})",file=f)
if before.channel==client.counting and Bclean.isdigit(): # counting alert
await before.reply(f"{auth.name} changed their message \"`{Bclean}`\")! The current number is `{client.Data['counting']}`",mention_author=False)
if before.channel==client.alphaCountC and not before.content.startswith("> "):
await after.delete()
# Profanity filter
for word in client.Data["blw"]:
filtered=scanMessage(word,Aclean)
if filtered:
await after.delete()
embed=discord.Embed(description=f"{auth.mention}'s message was edited to and deleted in {after.channel.mention}.\n\"{filtered}\"",color=discord.Color.red())
await client.alertC.send(embed=embed)
@client.event
async def on_raw_reaction_add(payload:discord.RawReactionActionEvent):
emoji:discord.partial_emoji.PartialEmoji=payload.emoji
emojiAuth:discord.Member=client.basement.get_member(payload.user_id)
try: channel:discord.TextChannel=await client.fetch_channel(payload.channel_id)
except: return
message:discord.Message=await channel.fetch_message(payload.message_id)
if payload.channel_id==858156662703128577: # polls channel
upEmoji:discord.Emoji=client.get_emoji(858556326548340746)
downEmoji:discord.Emoji=client.get_emoji(858556294743064576)
if not emoji in (upEmoji,downEmoji) and message.author==client.user:
await message.remove_reaction(emoji,emojiAuth)
return
try:
ups:discord.Reaction=list(filter(lambda x: x.emoji==upEmoji, message.reactions))[0]
downs:discord.Reaction=list(filter(lambda x: x.emoji==downEmoji, message.reactions))[0]
except IndexError: pass # this will happen if we cant find the up- and downvote history :/
except Exception as e: raise e
else:
downUsers=await downs.users().flatten()
async for upAuthor in ups.users():
if upAuthor in downUsers:
await message.remove_reaction(upEmoji,upAuthor)
await message.remove_reaction(downEmoji,upAuthor)
#elif emoji==client.get_emoji(935571232173199380):
# channel:discord.TextChannel=client.get_channel(payload.channel_id)
# await channel.send("\"Based\"? Are you kidding me? I spent a decent portion of my life writing all of that and your response to me is \"Based\"? Are you so mentally handicapped that the only word you can comprehend is \"Based\" - or are you just some idiot who thinks that with such a short response, he can make a statement about how meaningless what was written was? Well, I'll have you know that what I wrote was NOT meaningless, in fact, I even had my written work proof-read by several professors of literature. Don't believe me? I doubt you would, and your response to this will probably be \"Based\" once again. Do I give a ****? No, does it look like I give even the slightest piece of anything about five fricking letters? I bet you took the time to type those five letters too, I bet you sat there and chuckled to yourself for 20 hearty seconds before pressing \"send\". You're so fricking pathetic. I'm honestly considering directing you to a psychiatrist, but I'm simply far too nice to do something like that. You, however, will go out of your way to make a fool out of someone by responding to a well-thought-out, intelligent, or humorous statement that probably took longer to write than you can last in bed with a chimpanzee. What do I have to say to you? Absolutely nothing. I couldn't be bothered to respond to such a worthless attempt at a response. Do you want \"Based\" on your gravestone?")
# red flag
if emoji==client.get_emoji(940789559829082212):
await message.remove_reaction(emoji,emojiAuth)
embed=discord.Embed(title="Red Flag!",description=f"**{emojiAuth.display_name}** red flagged [this message]({message.jump_url})!",color=discord.Color.red())
await client.modGenC.send(embed=embed)
# will add the specified reaction role, otherwise, removes the emoji.
if payload.channel_id==client.Data["RR"]["channel"] and not emojiAuth.bot:
if emoji.name in client.Data["RR"]["table"]:
role=client.basement.get_role(int(client.Data["RR"]["table"][emoji.name]))
await emojiAuth.add_roles(role)
else: await message.remove_reaction(emoji,emojiAuth)
@client.event
async def on_raw_reaction_remove(payload:discord.RawReactionActionEvent):
emoji:discord.partial_emoji.PartialEmoji=payload.emoji
emojiAuth:discord.Member=client.basement.get_member(payload.user_id)
try: channel:discord.TextChannel=await client.fetch_channel(payload.channel_id)
except: return
message:discord.Message=await channel.fetch_message(payload.message_id)
if payload.channel_id==client.Data["RR"]["channel"] and not emojiAuth.bot:
if emoji.name in client.Data["RR"]["table"]:
role=client.basement.get_role(int(client.Data["RR"]["table"][emoji.name]))
await emojiAuth.remove_roles(role)
else: await message.remove_reaction(emoji,emojiAuth)
@client.event
async def on_message(message:discord.Message):
msg:str=message.content # get content (as opposed to the line below, content returns mentions and such)
clean:str=message.clean_content # removes mentions and the like
auth:discord.Member=message.author # get author
_dt:str=datet.now().strftime("%m/%d/%Y %H:%M:%S") # get current time/date
if auth==client.user or auth.bot: # prevent self or other bots from initiating basementbot interactions
return
# is muted check
#if client.Data[auth.id]["isMuted"]:
# await message.delete() # delete the message, ofc
# await auth.send(f"You have been muted, please contact an Admin if you believe this is a mistake.") # notify the user
# try: channelName=message.channel.name
# except AttributeError: channelName="the DM"
#
# with open(f"{client.dir}/logs/{message.channel.id}.txt", "a", encoding="utf-8") as f: # record the muted message, just in case ;)
# print(f"{_dt} {auth.name} ({auth.display_name}) ATTEMPTED to say \"{clean}\" in {channelName}", file=f)
# return
# handle case reply for logging
try:
reply=message.reference
if reply:
rAuth:discord.Member=reply.resolved.author
said=f"replied to {rAuth.display_name} ({reply.message_id}) with"
else:
said="said"
except: said="replied to someone with"
with open(f"{dirname(__file__)}/logs/{message.channel.id}.txt", "a", encoding="utf-8") as f: # record message. this is useful. very useful. i love data. lots of data
print(f"{_dt} {auth.name} ({auth.display_name}) {said} \"{clean}\" (path: {message.channel.id}/{message.id})", file=f)
if message.channel==client.testC:
print(f"{_dt} [BasementBot] {auth.display_name} - {msg}")
#print(profanity_filter.extra_profane_word_dictionaries)
#################################### blacklisted word check ####################################
if (message.channel.id!=932125853003943956 and clean.lower()!="ass"): # don't check for ass in the #alphabet-counting channel
# If adminRole is in the author's role list, end the check.
if client.adminRole in auth.roles:
pass
else:
for word in client.Data["blw"]:
filtered=scanMessage(word,clean)
if filtered:
await message.delete()
await client.alertC.send(embed=discord.Embed(description=f"{auth.mention}'s message was deleted in {message.channel.mention}.\n\"{filtered}\"",color=discord.Color.red()))
client.deletedMessages.append(message.id)
return
################################################################################################