Skip to content
This repository was archived by the owner on Mar 25, 2023. It is now read-only.

Commit c1ce98e

Browse files
committed
Misc cleanup
Fully removed TTS Patched up a couple of inconsistencies Changed a few notes Changed all ' to " (with a few exceptions) Used f"" more often Minor code edits (The NSFW module was so neglected) This was really needed, and could use more cleanup (rewriting a few oddly / poorly written functions)
1 parent 9b46fc4 commit c1ce98e

File tree

6 files changed

+151
-207
lines changed

6 files changed

+151
-207
lines changed

__start__.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from time import sleep
44
import asyncio
55
import os
6-
auth = dotenv_values()['BOTAUTH']
6+
auth = dotenv_values()["BOTAUTH"]
77
print("Starting...",os.getcwd())
88
try:
99
from main import client,log
@@ -22,21 +22,21 @@ def log(content):
2222
except Exception as exc:
2323
log("[!] client.run exited: "+str(exc))
2424
log("Checking for updates for client...")
25-
for i in os.listdir('update'): #What a mess
25+
for i in os.listdir("update"): #What a mess
2626
log("[Updater] "+i)
2727
if i == "__start__.py":
28-
log("Please update __start__ manually instead of through auto-update. Trust me, you dont want that headache")
28+
log("Please update __start__ manually instead of through auto-update")
2929
continue
3030
trueName = i.replace("^","/")
3131
if trueName != i:
3232
log("Sub-folder detected: "+str(i.split("^")))
33-
newFile = open('update/'+i,newline='').read()
33+
newFile = open("update/"+i,newline="").read()
3434
backup = None
3535
if os.path.isfile(i):
36-
backup = open(trueName,newline='').read()
36+
backup = open(trueName,newline="").read()
3737
else:
3838
log("No backup can be made for "+trueName)
39-
oldFile = open(trueName,"w",newline='')
39+
oldFile = open(trueName,"w",newline="")
4040
try:
4141
oldFile.write(newFile)
4242
log("Successfully written update for "+trueName)
@@ -51,10 +51,10 @@ def log(content):
5151
else:
5252
log(f"[!] Update for {trueName} failed (No backup): "+str(exc))
5353
else:
54-
os.remove('update/'+i)
54+
os.remove("update/"+i)
5555
oldFile.close()
5656
log("Rebooting...")
5757
if platform.startswith("win"): #win32/win64
58-
os.system('start __start__.py')
58+
os.system("start __start__.py")
5959
else: #Assume linux - use sh
60-
os.system('./start.sh')
60+
os.system("./start.sh")

main.py

Lines changed: 57 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@
1414
import os
1515
prefix = "##"
1616
DevID = 260016427900076033
17-
logChannels = {'errors':872153712347467776,'boot-ups':872208035093839932} # These are different from the guild-defined LogChannel channels, these are essentially telemetry
18-
colours = {'info':0x5555DD,'error':0xFF0000,'success':0x00FF00,'warning':0xFFAA00,'plain':0xAAAAAA}
17+
logChannels = {"errors":872153712347467776,"boot-ups":872208035093839932} # These are different from the guild-defined LogChannel channels, these are essentially telemetry
18+
colours = {"info":0x5555DD,"error":0xFF0000,"success":0x00FF00,"warning":0xFFAA00,"plain":0xAAAAAA}
1919

2020
#Base functions
2121
def exists(table,value): #Wanna reduce the try except spam checking for possible values
@@ -25,53 +25,54 @@ def exists(table,value): #Wanna reduce the try except spam checking for possible
2525
except:
2626
return False
2727
def tempFile(extension="txt"):
28-
name = "storage/temp/"+str(time.time())+"."+extension
28+
name = f"storage/temp/{str(time.time())}.{extension}"
2929
open(name,"x")
3030
return name
3131
def currentDate():
32-
return str(datetime.fromtimestamp(time.time()//1)) #Long function list be like
32+
return str(datetime.fromtimestamp(time.time()//1))
3333
def log(content):
3434
print(f"[Log {currentDate()[11:]}]",content)
3535
try:
36-
open("storage/logs/"+currentDate()[:10]+".log","a").write(f"[{currentDate()[11:]}] "+content+"\n")
36+
open(f"storage/logs/{currentDate()[:10]}.log","a").write(f"[{currentDate()[11:]}] {content}\n")
37+
return True
3738
except Exception as exc:
38-
print("[Log] Failed to log!",exc)
39-
log("Starting main - the time is "+str(time.time())+" or "+currentDate())
39+
print("[Log] Failed to log!",currentDate(),exc)
40+
log(f"Starting main - the time is {str(time.time())} or {currentDate()}")
4041
def safeWriteToFile(filename,content,encoding="UTF-8"):
4142
backup = None
4243
if os.path.isfile(filename):
4344
try:
4445
backup = open(filename,"rb").read()
4546
except:
46-
log("[SafeWrite] Failed to open "+filename+" - Probably access issues")
47-
return
47+
log(f"[SafeWrite] Failed to open {filename} - Probably access issues")
48+
return False
4849
try:
4950
file = open(filename,"w",encoding=encoding)
5051
except:
51-
log("[SafeWrite] Failed to open "+filename+" - Probably access issues")
52-
return
52+
log(f"[SafeWrite] Failed to open {filename} - Probably access issues")
53+
return False
5354
try:
5455
file.write(content)
5556
except Exception as exc:
5657
file.close()
5758
if backup:
5859
open(filename,"wb").write(backup)
59-
log("[SafeWrite] Failed to write to "+filename+": "+str(exc))
60+
log(f"[SafeWrite] Failed to write to {filename}: "+str(exc))
6061
else:
61-
log("[SafeWrite] Failed to write to "+filename+" with no backup available: "+str(exc))
62-
return
62+
log(f"[SafeWrite] Failed to write to {filename} with no backup available: "+str(exc))
63+
return False
6364
print("[SafeWrite] Successfully wrote to "+filename)
6465
return True
65-
multList = {"s":1,"m":60,"h":3600,"d":86400}
66+
timeMultList = {"s":1,"m":60,"h":3600,"d":86400}
6667
def strToTimeAdd(duration):
6768
timeMult = duration[-1].lower()
6869
timeAmount = duration[:-1]
6970
try:
7071
timeAmount = int(timeAmount)
7172
except:
7273
return False,"timeAmount must be an integer"
73-
if timeMult in multList:
74-
return True,timeAmount*multList[timeMult]
74+
if timeMult in timeMultList:
75+
return True,timeAmount*timeMultList[timeMult]
7576
else:
7677
return False,"Time period must be s, m, h or d"
7778
def simplifySeconds(seconds): #Feels like it could be cleaner, but eh
@@ -95,7 +96,7 @@ def simplifySeconds(seconds): #Feels like it could be cleaner, but eh
9596
returnString = (p==0 and str(days)+" day(s)") or (p==1 and str(days)+" day(s) and "+returnString) or str(days)+" day(s), "+returnString
9697
return returnString
9798
fromdict = discord.Embed.from_dict
98-
numRegex = regex.compile('\d+')
99+
numRegex = regex.compile("\d+")
99100
findMediaRegex = regex.compile("https?://((cdn|media)\.discordapp\.(com|net)/attachments/|tenor\.com/view/)")
100101

101102
#GMT
@@ -175,7 +176,7 @@ def RemoveChannelClear(self,channel): # Read above
175176
async def AddToFilter(self,msg,buffer):
176177
if buffer == None: # Failsafe, just in case
177178
return
178-
print("[Filter] Msg Filtered ->",msg.content,buffer)
179+
print("[Filter] Msg Filtered ->",buffer,msg.content)
179180
if buffer <= 0:
180181
try:
181182
await msg.delete()
@@ -347,17 +348,17 @@ async def Run(self,msg,args,bypassRL=False):
347348
return True,0
348349
async def doTheCheck(msg,args,commandTable): #Dont wanna type this 3 times
349350
arg0 = args[0]
350-
if '\n' in arg0:
351-
args[0] = arg0.split('\n')[0]
352-
args.insert(1,arg0.split('\n')[1])
351+
if "\n" in arg0:
352+
args[0] = arg0.split("\n")[0]
353+
args.insert(1,arg0.split("\n")[1])
353354
c = msg.content
354355
for command in commandTable:
355356
cregion = len(prefix+command) #command region
356357
if prefix+command == c[:cregion] and (not exists(c,cregion) or c[cregion] == " " or c[cregion] == "\n"):
357358
success,result = await commandTable[command].Run(msg,args)
358359
if not success:
359360
if result != -1: # If first repeat:
360-
await msg.channel.send(embed=fromdict({'title':'Slow Down','description':'That command is limited for '+simplifySeconds(math.floor(result))+' more seconds','color':colours['warning']}),delete_after=result)
361+
await msg.channel.send(embed=fromdict({"title":"Slow Down","description":f"That command is limited for {simplifySeconds(math.floor(result))} more seconds","color":colours["warning"]}),delete_after=result)
361362
return True
362363

363364
#Reaction listening
@@ -430,7 +431,7 @@ async def cloneChannel(channelid):
430431
gmt.ChannelLimits.pop(channelid)
431432
await channel.delete()
432433
newchannel.position = channel.position #Because clone doesnt include position
433-
await newchannel.send(embed=fromdict({'title':'Success','description':channel.name+' has been re-made and cleared','color':colours['success']}),delete_after=60)
434+
await newchannel.send(embed=fromdict({"title":"Success","description":channel.name+" has been re-made and cleared","color":colours["success"]}),delete_after=60)
434435
print("[CloneChannel] Successfully cloned channel",channel.name)
435436
return newchannel
436437
except Exception as exc:
@@ -439,7 +440,7 @@ def findVoiceClient(guildId): #Find the relevant voice client object for the spe
439440
for voiceObj in client.voice_clients:
440441
if voiceObj.guild.id == guildId:
441442
return voiceObj
442-
VCList = {}
443+
VCList = {} #Unmaintained and possibly broken
443444
async def connectToVC(channel,idleTimeout=60,ignorePlaying=False):
444445
vc = findVoiceClient(channel.guild.id)
445446
if vc:
@@ -466,33 +467,33 @@ async def on_error(error,*args,**kwargs):
466467
try:
467468
causingCommand = args[0].content
468469
except:
469-
causingCommand = args[0]
470+
causingCommand = str(args[0])
470471
else:
471472
causingCommand = "<none>"
472-
log("[Fatal Error] Causing command: "+str(causingCommand)+"\nError:")
473+
log(f"[Fatal Error] Causing command: {causingCommand}\nError:")
473474
traceback.print_exc(file=sys.stderr)
474475
try: #Logging
475476
errorFile = tempFile()
476-
file = open(errorFile,"w",encoding="UTF-8",newline='') #Linux doesnt support ansi?
477+
file = open(errorFile,"w",encoding="UTF-16",newline="") #UTF-16 just incase it all goes to hell
477478
try:
478479
traceback.print_exc(file=file)
479480
except Exception as exc:
480481
log("[Fatal Error] Error Log file failed to write: "+str(exc))
481482
pass
482483
file.close()
483-
await client.get_channel(logChannels['errors']).send("Error in client\nTime: "+currentDate()+"\nCausing command: "+str(causingCommand),file=discord.File(errorFile))
484+
await client.get_channel(logChannels["errors"]).send(f"Error in client\nTime: {currentDate()}\nCausing command: {causingCommand}",file=discord.File(errorFile))
484485
os.remove(errorFile)
485486
except Exception as exc:
486-
log("[Fatal Error] Failed to log: "+currentDate()+str(exc))
487+
log(f"[Fatal Error] Failed to log error: {currentDate()} {str(exc)}")
487488
uptime = 0
488489
@client.event
489490
async def on_ready():
490491
global uptime
491-
await client.change_presence(activity=discord.Game(name='##cmds'))
492-
log('connected v'+discord.__version__)
492+
await client.change_presence(activity=discord.Game(name="##cmds"))
493+
log("connected v"+discord.__version__)
493494
uptime = time.time()//1
494495
try: #Notifying of start-up
495-
await client.get_channel(logChannels['boot-ups']).send("Ive connected at "+currentDate())
496+
await client.get_channel(logChannels["boot-ups"]).send("Ive connected at "+currentDate())
496497
except:
497498
log("Failed to alert of bootup at "+currentDate())
498499
@client.event
@@ -501,15 +502,15 @@ async def on_message(msg):
501502
if msg.guild:
502503
await getMegaTable(msg).FilterMessage(msg)
503504
elif msg.author.id != client.user.id:
504-
await msg.channel.send(embed=fromdict({'title':'Not here','description':'This bot can only be used in a server, and not dms','color':colours['error']}))
505+
await msg.channel.send(embed=fromdict({"title":"Not here","description":"This bot can only be used in a server, and not dms","color":colours["error"]}))
505506
return
506507
gmt = getMegaTable(msg)
507508
await gmt.FilterMessage(msg)
508509
if type(msg.author) == discord.User: #Webhook
509510
return
510-
if await gmt.CheckConfirmation(msg):
511-
return
512-
args = msg.content.split(' ') #Please keep in mind the first argument is the calling command
511+
if await gmt.CheckConfirmation(msg): #Confirmations arent commands, simple as that
512+
return await checkHistoryClear(msg)
513+
args = msg.content.split(" ") #Please keep in mind the first argument is the calling command
513514
if msg.author.id == DevID:
514515
if await doTheCheck(msg,args,devCommands):
515516
return
@@ -518,26 +519,26 @@ async def on_message(msg):
518519
return
519520
if await doTheCheck(msg,args,userCommands):
520521
return
521-
await checkHistoryClear(msg) #Since its fired after a command, add a backup here
522+
await checkHistoryClear(msg) #Since its fired after a command, add a backup check here
522523
@client.event
523524
async def on_raw_message_edit(msg): #On message edit to avoid bypassing
524525
try:
525-
messageObj = await discord.PartialMessage(channel=client.get_channel(int(msg.data['channel_id'])),id=int(msg.data['id'])).fetch()
526+
messageObj = await discord.PartialMessage(channel=client.get_channel(int(msg.data["channel_id"])),id=int(msg.data["id"])).fetch()
526527
except:
527-
pass #Dont care if this errors since it bloody will and its not an issue
528+
pass
528529
else:
529530
await getMegaTable(messageObj).FilterMessage(messageObj)
530531
@client.event
531532
async def on_reaction_add(reaction,user):
532-
if user.id == client.user.id: #If its me
533+
if user.id == client.user.id: #If its the bot
533534
return
534535
ListenListCache = ReactionListenList
535536
for listener in ListenListCache:
536537
await listener.Check(reaction.message,user,reaction.emoji)
537538
@client.event
538539
async def on_guild_join(guild):
539-
guildMegaTable[guild.id] = GuildObject(guild.id) # Force default settings
540-
getMegaTable(guild).InviteTrack = await getGuildInviteStats(guild)
540+
guildMegaTable[guild.id] = GuildObject(guild.id) #Force default settings
541+
getMegaTable(guild).InviteTrack = await getGuildInviteStats(guild) #Does this even work?
541542
@client.event
542543
async def on_member_join(member):
543544
guild = member.guild
@@ -615,12 +616,12 @@ async def constantChannelCheck(): #For queued channel clearing
615616
async def updateConfigFiles(): #So i dont have pre-coded values
616617
try:
617618
for guild in client.guilds:
618-
safeWriteToFile("storage/settings/"+str(guild.id)+".json",json.dumps(getMegaTable(guild).CreateSave()))
619+
safeWriteToFile(f"storage/settings/{str(guild.id)}.json",json.dumps(getMegaTable(guild).CreateSave()))
619620
except Exception as exc:
620621
log("[!] UpdateConfig Exception: "+str(exc))
621622
updateConfigFiles.start()
622623
@tasks.loop(seconds=2)
623-
async def VCCheck():
624+
async def VCCheck(): #Auto disconnect
624625
try:
625626
for vc in VCList:
626627
if vc.is_playing():
@@ -630,7 +631,7 @@ async def VCCheck():
630631
except Exception as exc:
631632
log("[!] VCCheck Exception: "+str(exc))
632633
VCCheck.start()
633-
@tasks.loop(seconds=5)
634+
@tasks.loop(seconds=15)
634635
async def keepGuildInviteUpdated():
635636
for guild in client.guilds:
636637
gmt = getMegaTable(guild)
@@ -639,14 +640,14 @@ async def keepGuildInviteUpdated():
639640
keepGuildInviteUpdated.start()
640641

641642
#User Commands
642-
async def forceUpdate(msg,args):
643+
async def forceUpdate(msg,args): #(Safely) close the bot down for updating
643644
global stopCycling
644645
log("Client was force-exited via forceUpdate() "+str(time.time()))
645646
log("Hanging until messageCheck has finished its cycle or 20s, whatever is shorter")
646647
stopCycling = True
647648
sleepTime = 0
648649
while True:
649-
if finishedLastCycle == True or sleepTime>=20: #? idk
650+
if finishedLastCycle == True or sleepTime>=20: #Timeout worries
650651
break
651652
sleepTime+=1
652653
await asyncio.sleep(1)
@@ -691,13 +692,13 @@ async def cmds(msg,args):
691692
Command(["commands","cmds"],cmds,1,"List all commands",{"group":False},None,"General")
692693
async def publicVote(msg,args):
693694
if len(args) < 2:
694-
await msg.channel.send(embed=fromdict({'title':'Error','description':'You gotta include the thing to vote on','color':colours['error']}),delete_after=30)
695+
await msg.channel.send(embed=fromdict({"title":"Error","description":"You gotta include the thing to vote on","color":colours["error"]}),delete_after=10)
695696
return
696697
attachments = msg.attachments
697698
imageUrl = (exists(attachments,0) and attachments[0].url) or ""
698699
author = msg.author
699700
wantedReactions = []
700-
findWantedReaction = regex.compile('^{[^\]]+}$')
701+
findWantedReaction = regex.compile("^{[^\]]+}$")
701702
index = -1
702703
for i in args: #Get user-defined reactions ( [:reaction:] )
703704
index += 1
@@ -708,8 +709,8 @@ async def publicVote(msg,args):
708709
msgContent = ""
709710
for i in args:
710711
if i: #mhm
711-
msgContent = msgContent + i + " "
712-
voteMsg = await msg.channel.send(embed=fromdict({'author':{'name':author.name+"#"+author.discriminator+' is calling a vote','icon_url':str(author.avatar_url)},'description':msgContent,'image':{'url':imageUrl},'color':colours['info']}))
712+
msgContent = msgContent+i+" "
713+
voteMsg = await msg.channel.send(embed=fromdict({"author":{"name":f"{author.name}#{author.discriminator} is calling a vote","icon_url":str(author.avatar_url)},"description":msgContent,"image":{"url":imageUrl},"color":colours["info"]}))
713714
try:
714715
await msg.delete()
715716
except:
@@ -726,7 +727,7 @@ async def publicVote(msg,args):
726727
Command("vote",publicVote,10,"Make a public vote about anything with an optional image",{"text":True,"imagefile":False},None,"General")
727728

728729
#Module importing
729-
log('attempting import')
730+
log("attempting import")
730731
''' Load modules from the modules folder
731732
Only use this for storing commands, as load order is random
732733
This is so i dont clog up the entirety of this main script with like 2k lines '''
@@ -753,14 +754,14 @@ async def loadModulesAsync(msg,args):
753754

754755
#Finish off - load configs
755756
log("done commands")
756-
for i in os.listdir('storage/settings'):
757+
for i in os.listdir("storage/settings"):
757758
try:
758-
j = json.loads(open('storage/settings/'+i).read())
759+
j = json.loads(open("storage/settings/"+i).read())
759760
except:
760761
log("[JSON] Load failed for file "+i)
761762
else:
762763
try:
763-
getMegaTable(j['Guild']).LoadSave(j)
764+
getMegaTable(j["Guild"]).LoadSave(j)
764765
except:
765766
log("[JSON] Guild index failed for file "+i)
766767
log("loaded config")

0 commit comments

Comments
 (0)