style: format with black

This commit is contained in:
Price Hiller 2024-10-01 18:27:04 -05:00
parent 3bea54be88
commit 323344aa2f
Signed by: Price
GPG Key ID: C3FADDE7A8534BEB
6 changed files with 118 additions and 72 deletions

View File

@ -25,22 +25,29 @@ class Group(commands.Cog, name="group"):
membsup.append(memb.id) membsup.append(memb.id)
if len(membsup) > 0: if len(membsup) > 0:
memupcur = self.client.squadjs.cursor(buffered=True) memupcur = self.client.squadjs.cursor(buffered=True)
in_params = ','.join(['%s'] * len(membsup)) in_params = ",".join(["%s"] * len(membsup))
sqlstate = "SELECT * FROM DBLog_SteamUsers WHERE discordID IN (%s)" % in_params sqlstate = (
"SELECT * FROM DBLog_SteamUsers WHERE discordID IN (%s)" % in_params
)
log.info(sqlstate) log.info(sqlstate)
memupcur.execute(sqlstate, membsup) memupcur.execute(sqlstate, membsup)
udata = memupcur.fetchall() udata = memupcur.fetchall()
for data in udata: 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.commit()
self.client.squadjs.close() 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 role.id in self.client.whitelistGrps.keys():
if perms is not None: if perms is not None:
self.client.whitelistGrps[role.id].squadPerms = perms self.client.whitelistGrps[role.id].squadPerms = perms
@ -54,11 +61,7 @@ class Group(commands.Cog, name="group"):
await self.updateRole(role) await self.updateRole(role)
@app_commands.command() @app_commands.command()
async def update( async def update(self, interaction: discord.Interaction, role: discord.Role):
self,
interaction: discord.Interaction,
role: discord.Role
):
if role.id in self.client.whitelistGrps.keys(): if role.id in self.client.whitelistGrps.keys():
await interaction.response.send_message("updating role!") await interaction.response.send_message("updating role!")
await self.updateRole(role) await self.updateRole(role)
@ -75,10 +78,7 @@ class Group(commands.Cog, name="group"):
@app_commands.command() @app_commands.command()
async def addperm( async def addperm(
self, self, interaction: discord.Interaction, role: discord.Role, perms: str
interaction: discord.Interaction,
role: discord.Role,
perms: str
): ):
await self.baseperm(interaction, role, perms) await self.baseperm(interaction, role, perms)
@ -88,7 +88,7 @@ class Group(commands.Cog, name="group"):
interaction: discord.Interaction, interaction: discord.Interaction,
shortname: str, shortname: str,
remoteurl: str, remoteurl: str,
perms: str = 'whitelist' perms: str = "whitelist",
): ):
if os.path.exists(f"wlgrps/{shortname}.cfg"): if os.path.exists(f"wlgrps/{shortname}.cfg"):
await interaction.response.send_message("Already exists!") await interaction.response.send_message("Already exists!")

View File

@ -26,28 +26,46 @@ class Whitelist(commands.Cog):
return return
updatecur = self.client.squadjs.cursor(buffered=True) updatecur = self.client.squadjs.cursor(buffered=True)
try: try:
updatecur.execute(self.client.squadjs_updateDiscordID, (interaction.user.id, steam64)) updatecur.execute(
self.client.squadjs_updateDiscordID, (interaction.user.id, steam64)
)
rowsaffected = updatecur.rowcount rowsaffected = updatecur.rowcount
if rowsaffected <= 0: 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: if updatecur.rowcount <= 0:
await interaction.response.send_message("Cound not find SteamID!") await interaction.response.send_message("Cound not find SteamID!")
else: else:
for urole in interaction.user.roles: for urole in interaction.user.roles:
if urole.id in self.client.whitelistGrps.keys(): 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() 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() self.client.squadjs.commit()
return return
except mysql.connector.Error as err: except mysql.connector.Error as err:
log.error("MYSQL error!") 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 return
for urole in interaction.user.roles: for urole in interaction.user.roles:
if urole.id in self.client.whitelistGrps.keys(): if urole.id in self.client.whitelistGrps.keys():
disusername = interaction.user.nick if interaction.user.nick is not None else interaction.user.name disusername = (
self.client.whitelistGrps[urole.id].addMember(config.WhitelistMember(interaction.user.id, disusername, steam64)) 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.commit()
self.client.squadjs.close() 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."
)

View File

@ -6,6 +6,7 @@ from autowl.config import DiscordClientConfig
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class CustomFormat(logging.Formatter): class CustomFormat(logging.Formatter):
grey = "\x1b[38;20m" grey = "\x1b[38;20m"
yellow = "\x1b[33;20m" yellow = "\x1b[33;20m"

View File

@ -11,21 +11,21 @@ log = logging.getLogger(__name__)
class Bot(commands.Bot): class Bot(commands.Bot):
squadjs_updateDiscordID = ("UPDATE DBLog_SteamUsers SET discordID = %s " squadjs_updateDiscordID = (
"WHERE steamID = %s") "UPDATE DBLog_SteamUsers SET discordID = %s " "WHERE steamID = %s"
)
squadjs_findByDiscordID = ("SELECT * FROM DBLog_SteamUsers " squadjs_findByDiscordID = "SELECT * FROM DBLog_SteamUsers " "WHERE discordID = %s"
"WHERE discordID = %s")
whitelistGrps = {} whitelistGrps = {}
if not os.path.exists('./wlgrps'): if not os.path.exists("./wlgrps"):
os.makedirs('./wlgrps') os.makedirs("./wlgrps")
else: else:
for wlfile in os.listdir('./wlgrps'): for wlfile in os.listdir("./wlgrps"):
filename = os.fsdecode(wlfile) filename = os.fsdecode(wlfile)
if filename.endswith('.json'): if filename.endswith(".json"):
file = open(f'./wlgrps/{filename}', 'r') file = open(f"./wlgrps/{filename}", "r")
wlgrp: config.WhitelistGroup = jsonpickle.decode(file.read()) wlgrp: config.WhitelistGroup = jsonpickle.decode(file.read())
whitelistGrps[wlgrp.discord_role_id] = wlgrp whitelistGrps[wlgrp.discord_role_id] = wlgrp
@ -39,11 +39,18 @@ class Bot(commands.Bot):
intents=intents, intents=intents,
help_command=commands.DefaultHelpCommand(dm_help=True), help_command=commands.DefaultHelpCommand(dm_help=True),
) )
self.squadjs = mysql.connector.connect(user='squadjs', password=mysqlpass, self.squadjs = mysql.connector.connect(
host='asgard.orion-technologies.io', database='squadjs', use_pure=False) user="squadjs",
password=mysqlpass,
host="asgard.orion-technologies.io",
database="squadjs",
use_pure=False,
)
async def on_command(self, ctx: commands.Context): 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): async def on_ready(self):
log.info(f"Logged in as '{self.user}' ({self.user.id})") log.info(f"Logged in as '{self.user}' ({self.user.id})")
@ -92,7 +99,9 @@ class Bot(commands.Bot):
for addroleid in addroles: for addroleid in addroles:
if not (addroleid in self.whitelistGrps.keys()): if not (addroleid in self.whitelistGrps.keys()):
continue 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.commit()
self.squadjs.close() self.squadjs.close()

View File

@ -23,7 +23,7 @@ class WhitelistGroup:
squadPerms: str squadPerms: str
members: dict[str, WhitelistMember] members: dict[str, WhitelistMember]
def __init__(self, name, roleID, permissions='reserve'): def __init__(self, name, roleID, permissions="reserve"):
self.name = name self.name = name
self.discord_role_id = roleID self.discord_role_id = roleID
self.squadPerms = permissions self.squadPerms = permissions
@ -49,7 +49,9 @@ class WhitelistGroup:
wlFile.write(f"//{self.name}\n") wlFile.write(f"//{self.name}\n")
for wlmem in self.members: for wlmem in self.members:
memb = self.members[wlmem] 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() wlFile.close()
def addMember(self, member): def addMember(self, member):
@ -59,6 +61,6 @@ class WhitelistGroup:
pass pass
def delMember(self, discordID): def delMember(self, discordID):
self.members.pop(f'{discordID}') self.members.pop(f"{discordID}")
self.updateFile() self.updateFile()
self.updateWL() self.updateWL()

View File

@ -16,11 +16,11 @@ PORT = 8000
class serveRA(http.server.SimpleHTTPRequestHandler): class serveRA(http.server.SimpleHTTPRequestHandler):
def do_GET(self): def do_GET(self):
query = parse_qs(urlparse(self.path).query) query = parse_qs(urlparse(self.path).query)
if 'grpName' in query: if "grpName" in query:
self.send_response(200) self.send_response(200)
self.send_header("Content-type", "text") self.send_header("Content-type", "text")
self.end_headers() self.end_headers()
grpName = query['grpName'][0] grpName = query["grpName"][0]
grpfile = "./" grpfile = "./"
if os.path.exists(f"./wlgrps/{grpName}.cfg"): if os.path.exists(f"./wlgrps/{grpName}.cfg"):
grpfile += 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) print("could not find admins file!", file=stderr)
return return
try: try:
file = open(grpfile, 'rb') file = open(grpfile, "rb")
firstline = file.readline().decode('utf-8') firstline = file.readline().decode("utf-8")
file.seek(0) file.seek(0)
if firstline.startswith('remotelist='): if firstline.startswith("remotelist="):
remote = firstline.split('=')[1].strip() remote = firstline.split("=")[1].strip()
response = requests.get(remote, headers={'Accept': 'text/html,*/*'}) response = requests.get(remote, headers={"Accept": "text/html,*/*"})
print(f"remote list came back with status code {response.status_code}") print(
f"remote list came back with status code {response.status_code}"
)
if response.status_code == 200: if response.status_code == 200:
responsetext = response.text responsetext = response.text
config = file.read().decode('utf-8') config = file.read().decode("utf-8")
confgrps = re.findall(r"permissions/(.+)=(.+)", config, flags=re.M) confgrps = re.findall(
r"permissions/(.+)=(.+)", config, flags=re.M
)
baseperm = 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: for congrp in confgrps:
responsetext = re.sub(rf"^Group=({congrp[0]}):(.+)", rf"Group=\1:{congrp[1]}", responsetext, flags=re.M) responsetext = re.sub(
self.wfile.write(responsetext.encode('utf-8')) rf"^Group=({congrp[0]}):(.+)",
with open(f"./wlgrps/backup-{grpName}.cfg", 'wb') as backupfile: rf"Group=\1:{congrp[1]}",
backupfile.write(responsetext.encode('utf-8')) 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() backupfile.close()
else: else:
backupfile = open(f"./wlgrps/backup-{grpName}.cfg", 'rb') backupfile = open(f"./wlgrps/backup-{grpName}.cfg", "rb")
self.copyfile(backupfile, self.wfile) self.copyfile(backupfile, self.wfile)
backupfile.close() backupfile.close()
else: else:
self.copyfile(file, self.wfile) self.copyfile(file, self.wfile)
file.close() file.close()
except: except:
print('failed to serve file!', file=stderr) print("failed to serve file!", file=stderr)
print(traceback.format_exc(), file=stderr) print(traceback.format_exc(), file=stderr)
else: 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 return
@ -71,7 +87,7 @@ def startServer():
print("trying to start...") print("trying to start...")
try: try:
with socketserver.ThreadingTCPServer(("", PORT), handler) as httpd: with socketserver.ThreadingTCPServer(("", PORT), handler) as httpd:
print('starting server!') print("starting server!")
httpd.serve_forever() httpd.serve_forever()
except: except:
print("server did not start trying again!") print("server did not start trying again!")