From 323344aa2f2d77176f6674f59ee65946ed8d01e4 Mon Sep 17 00:00:00 2001 From: Price Hiller Date: Tue, 1 Oct 2024 18:27:04 -0500 Subject: [PATCH] style: format with `black` --- autowl/Cogs/Group.py | 54 ++++++++++++++++++++-------------------- autowl/Cogs/Whitelist.py | 34 +++++++++++++++++++------ autowl/__main__.py | 1 + autowl/bot.py | 39 ++++++++++++++++++----------- autowl/config.py | 8 +++--- simpleFileServer.py | 54 ++++++++++++++++++++++++++-------------- 6 files changed, 118 insertions(+), 72 deletions(-) diff --git a/autowl/Cogs/Group.py b/autowl/Cogs/Group.py index 57f3d07..d3a6029 100644 --- a/autowl/Cogs/Group.py +++ b/autowl/Cogs/Group.py @@ -18,29 +18,36 @@ class Group(commands.Cog, name="group"): def __init__(self, client: Bot): self.client = client - async def updateRole(self, role:discord.Role): + async def updateRole(self, role: discord.Role): self.client.squadjs.connect() membsup = [] for memb in role.members: membsup.append(memb.id) if len(membsup) > 0: memupcur = self.client.squadjs.cursor(buffered=True) - in_params = ','.join(['%s'] * len(membsup)) - sqlstate = "SELECT * FROM DBLog_SteamUsers WHERE discordID IN (%s)" % in_params + in_params = ",".join(["%s"] * len(membsup)) + sqlstate = ( + "SELECT * FROM DBLog_SteamUsers WHERE discordID IN (%s)" % in_params + ) log.info(sqlstate) memupcur.execute(sqlstate, membsup) udata = memupcur.fetchall() for data in udata: - self.client.whitelistGrps[role.id].addMember(config.WhitelistMember(data[2], data[1], data[0])) + self.client.whitelistGrps[role.id].addMember( + config.WhitelistMember(data[2], data[1], data[0]) + ) self.client.squadjs.commit() self.client.squadjs.close() + async def baseperm( + self, interaction: discord.Interaction, role: discord.Role, perms: str + ): - async def baseperm(self, interaction: discord.Interaction, role: discord.Role, perms: str): - - await interaction.response.send_message("Whitelist group successfully added/updated") + await interaction.response.send_message( + "Whitelist group successfully added/updated" + ) if role.id in self.client.whitelistGrps.keys(): if perms is not None: self.client.whitelistGrps[role.id].squadPerms = perms @@ -54,11 +61,7 @@ class Group(commands.Cog, name="group"): await self.updateRole(role) @app_commands.command() - async def update( - self, - interaction: discord.Interaction, - role: discord.Role - ): + async def update(self, interaction: discord.Interaction, role: discord.Role): if role.id in self.client.whitelistGrps.keys(): await interaction.response.send_message("updating role!") await self.updateRole(role) @@ -67,28 +70,25 @@ class Group(commands.Cog, name="group"): @app_commands.command() async def add( - self, - interaction: discord.Interaction, - role: discord.Role, + self, + interaction: discord.Interaction, + role: discord.Role, ): await self.baseperm(interaction, role, "reserve") @app_commands.command() async def addperm( - self, - interaction: discord.Interaction, - role: discord.Role, - perms: str + self, interaction: discord.Interaction, role: discord.Role, perms: str ): await self.baseperm(interaction, role, perms) @app_commands.command() async def addremote( - self, - interaction: discord.Interaction, - shortname: str, - remoteurl: str, - perms: str = 'whitelist' + self, + interaction: discord.Interaction, + shortname: str, + remoteurl: str, + perms: str = "whitelist", ): if os.path.exists(f"wlgrps/{shortname}.cfg"): await interaction.response.send_message("Already exists!") @@ -102,9 +102,9 @@ class Group(commands.Cog, name="group"): @app_commands.command() async def remove( - self, - interaction: discord.Interaction, - role: discord.Role, + self, + interaction: discord.Interaction, + role: discord.Role, ): if not self.client.whitelistGrps.get(role.id): await interaction.response.send_message( diff --git a/autowl/Cogs/Whitelist.py b/autowl/Cogs/Whitelist.py index f69a3b0..39192d2 100644 --- a/autowl/Cogs/Whitelist.py +++ b/autowl/Cogs/Whitelist.py @@ -26,28 +26,46 @@ class Whitelist(commands.Cog): return updatecur = self.client.squadjs.cursor(buffered=True) try: - updatecur.execute(self.client.squadjs_updateDiscordID, (interaction.user.id, steam64)) + updatecur.execute( + self.client.squadjs_updateDiscordID, (interaction.user.id, steam64) + ) rowsaffected = updatecur.rowcount if rowsaffected <= 0: - updatecur.execute(self.client.squadjs_findByDiscordID, [interaction.user.id]) + updatecur.execute( + self.client.squadjs_findByDiscordID, [interaction.user.id] + ) if updatecur.rowcount <= 0: await interaction.response.send_message("Cound not find SteamID!") else: for urole in interaction.user.roles: if urole.id in self.client.whitelistGrps.keys(): - self.client.whitelistGrps[urole.id].members[f"{interaction.user.id}"].steam64 = steam64 + self.client.whitelistGrps[urole.id].members[ + f"{interaction.user.id}" + ].steam64 = steam64 self.client.whitelistGrps[urole.id].updateGroup() - await interaction.response.send_message("SteamID already linked, roles updated.") + await interaction.response.send_message( + "SteamID already linked, roles updated." + ) self.client.squadjs.commit() return except mysql.connector.Error as err: log.error("MYSQL error!") - await interaction.response.send_message("There was an internal server error, pls contact skillet") + await interaction.response.send_message( + "There was an internal server error, pls contact skillet" + ) return for urole in interaction.user.roles: if urole.id in self.client.whitelistGrps.keys(): - disusername = interaction.user.nick if interaction.user.nick is not None else interaction.user.name - self.client.whitelistGrps[urole.id].addMember(config.WhitelistMember(interaction.user.id, disusername, steam64)) + disusername = ( + interaction.user.nick + if interaction.user.nick is not None + else interaction.user.name + ) + self.client.whitelistGrps[urole.id].addMember( + config.WhitelistMember(interaction.user.id, disusername, steam64) + ) self.client.squadjs.commit() self.client.squadjs.close() - await interaction.response.send_message(f"discord is linked to steamID, roles updated.") + await interaction.response.send_message( + f"discord is linked to steamID, roles updated." + ) diff --git a/autowl/__main__.py b/autowl/__main__.py index be87568..8be4a18 100644 --- a/autowl/__main__.py +++ b/autowl/__main__.py @@ -6,6 +6,7 @@ from autowl.config import DiscordClientConfig log = logging.getLogger(__name__) + class CustomFormat(logging.Formatter): grey = "\x1b[38;20m" yellow = "\x1b[33;20m" diff --git a/autowl/bot.py b/autowl/bot.py index 9cf8f7a..0000aad 100644 --- a/autowl/bot.py +++ b/autowl/bot.py @@ -11,21 +11,21 @@ log = logging.getLogger(__name__) class Bot(commands.Bot): - squadjs_updateDiscordID = ("UPDATE DBLog_SteamUsers SET discordID = %s " - "WHERE steamID = %s") + squadjs_updateDiscordID = ( + "UPDATE DBLog_SteamUsers SET discordID = %s " "WHERE steamID = %s" + ) - squadjs_findByDiscordID = ("SELECT * FROM DBLog_SteamUsers " - "WHERE discordID = %s") + squadjs_findByDiscordID = "SELECT * FROM DBLog_SteamUsers " "WHERE discordID = %s" whitelistGrps = {} - if not os.path.exists('./wlgrps'): - os.makedirs('./wlgrps') + if not os.path.exists("./wlgrps"): + os.makedirs("./wlgrps") else: - for wlfile in os.listdir('./wlgrps'): + for wlfile in os.listdir("./wlgrps"): filename = os.fsdecode(wlfile) - if filename.endswith('.json'): - file = open(f'./wlgrps/{filename}', 'r') + if filename.endswith(".json"): + file = open(f"./wlgrps/{filename}", "r") wlgrp: config.WhitelistGroup = jsonpickle.decode(file.read()) whitelistGrps[wlgrp.discord_role_id] = wlgrp @@ -39,11 +39,18 @@ class Bot(commands.Bot): intents=intents, help_command=commands.DefaultHelpCommand(dm_help=True), ) - self.squadjs = mysql.connector.connect(user='squadjs', password=mysqlpass, - host='asgard.orion-technologies.io', database='squadjs', use_pure=False) + self.squadjs = mysql.connector.connect( + user="squadjs", + password=mysqlpass, + host="asgard.orion-technologies.io", + database="squadjs", + use_pure=False, + ) async def on_command(self, ctx: commands.Context): - log.info(f"{ctx.author} ({ctx.author.id}) invoked command: {ctx.command.name}, {ctx.message}") + log.info( + f"{ctx.author} ({ctx.author.id}) invoked command: {ctx.command.name}, {ctx.message}" + ) async def on_ready(self): log.info(f"Logged in as '{self.user}' ({self.user.id})") @@ -77,7 +84,7 @@ class Bot(commands.Bot): rmroles.remove(aftrole.id) log.info(f"roles found to remove from {disusername}: {rmroles}") for rmroleid in rmroles: - if not(rmroleid in self.whitelistGrps.keys()): + if not (rmroleid in self.whitelistGrps.keys()): continue self.whitelistGrps[rmroleid].delMember(before.id) @@ -90,9 +97,11 @@ class Bot(commands.Bot): addroles.remove(befrole.id) log.info(f"roles found to add to {disusername}: {addroles}") for addroleid in addroles: - if not(addroleid in self.whitelistGrps.keys()): + if not (addroleid in self.whitelistGrps.keys()): continue - self.whitelistGrps[addroleid].addMember(config.WhitelistMember(after.id, disusername, userdata[0])) + self.whitelistGrps[addroleid].addMember( + config.WhitelistMember(after.id, disusername, userdata[0]) + ) self.squadjs.commit() self.squadjs.close() diff --git a/autowl/config.py b/autowl/config.py index eff02af..93706f4 100644 --- a/autowl/config.py +++ b/autowl/config.py @@ -23,7 +23,7 @@ class WhitelistGroup: squadPerms: str members: dict[str, WhitelistMember] - def __init__(self, name, roleID, permissions='reserve'): + def __init__(self, name, roleID, permissions="reserve"): self.name = name self.discord_role_id = roleID self.squadPerms = permissions @@ -49,7 +49,9 @@ class WhitelistGroup: wlFile.write(f"//{self.name}\n") for wlmem in self.members: memb = self.members[wlmem] - wlFile.write(f"Admin={memb.steam64}:{self.name} //{memb.discord_username} ({memb.discord_id})\n") + wlFile.write( + f"Admin={memb.steam64}:{self.name} //{memb.discord_username} ({memb.discord_id})\n" + ) wlFile.close() def addMember(self, member): @@ -59,6 +61,6 @@ class WhitelistGroup: pass def delMember(self, discordID): - self.members.pop(f'{discordID}') + self.members.pop(f"{discordID}") self.updateFile() self.updateWL() diff --git a/simpleFileServer.py b/simpleFileServer.py index 3262578..c9cccda 100644 --- a/simpleFileServer.py +++ b/simpleFileServer.py @@ -16,11 +16,11 @@ PORT = 8000 class serveRA(http.server.SimpleHTTPRequestHandler): def do_GET(self): query = parse_qs(urlparse(self.path).query) - if 'grpName' in query: + if "grpName" in query: self.send_response(200) self.send_header("Content-type", "text") self.end_headers() - grpName = query['grpName'][0] + grpName = query["grpName"][0] grpfile = "./" if os.path.exists(f"./wlgrps/{grpName}.cfg"): grpfile += f"wlgrps/{grpName}.cfg" @@ -30,37 +30,53 @@ class serveRA(http.server.SimpleHTTPRequestHandler): print("could not find admins file!", file=stderr) return try: - file = open(grpfile, 'rb') - firstline = file.readline().decode('utf-8') + file = open(grpfile, "rb") + firstline = file.readline().decode("utf-8") file.seek(0) - if firstline.startswith('remotelist='): - remote = firstline.split('=')[1].strip() - response = requests.get(remote, headers={'Accept': 'text/html,*/*'}) - print(f"remote list came back with status code {response.status_code}") + if firstline.startswith("remotelist="): + remote = firstline.split("=")[1].strip() + response = requests.get(remote, headers={"Accept": "text/html,*/*"}) + print( + f"remote list came back with status code {response.status_code}" + ) if response.status_code == 200: responsetext = response.text - config = file.read().decode('utf-8') - confgrps = re.findall(r"permissions/(.+)=(.+)", config, flags=re.M) + config = file.read().decode("utf-8") + confgrps = re.findall( + r"permissions/(.+)=(.+)", config, flags=re.M + ) baseperm = re.findall(r"permissions=(.+)", config, flags=re.M) - responsetext = re.sub(r"Group=(.+):(.+)", fr'Group=\1:{baseperm[0]}', responsetext, flags=re.M) + responsetext = re.sub( + r"Group=(.+):(.+)", + rf"Group=\1:{baseperm[0]}", + responsetext, + flags=re.M, + ) for congrp in confgrps: - responsetext = re.sub(rf"^Group=({congrp[0]}):(.+)", rf"Group=\1:{congrp[1]}", responsetext, flags=re.M) - self.wfile.write(responsetext.encode('utf-8')) - with open(f"./wlgrps/backup-{grpName}.cfg", 'wb') as backupfile: - backupfile.write(responsetext.encode('utf-8')) + responsetext = re.sub( + rf"^Group=({congrp[0]}):(.+)", + rf"Group=\1:{congrp[1]}", + responsetext, + flags=re.M, + ) + self.wfile.write(responsetext.encode("utf-8")) + with open(f"./wlgrps/backup-{grpName}.cfg", "wb") as backupfile: + backupfile.write(responsetext.encode("utf-8")) backupfile.close() else: - backupfile = open(f"./wlgrps/backup-{grpName}.cfg", 'rb') + backupfile = open(f"./wlgrps/backup-{grpName}.cfg", "rb") self.copyfile(backupfile, self.wfile) backupfile.close() else: self.copyfile(file, self.wfile) file.close() except: - print('failed to serve file!', file=stderr) + print("failed to serve file!", file=stderr) print(traceback.format_exc(), file=stderr) else: - self.send_error(400, 'please specify the group to pull from', 'no grpName specified!') + self.send_error( + 400, "please specify the group to pull from", "no grpName specified!" + ) return @@ -71,7 +87,7 @@ def startServer(): print("trying to start...") try: with socketserver.ThreadingTCPServer(("", PORT), handler) as httpd: - print('starting server!') + print("starting server!") httpd.serve_forever() except: print("server did not start trying again!")