Skip to content

Commit ee1b87b

Browse files
rahmcoffjp00p
andauthored
Cleanup files in the command folder (#251)
* Cleanup files in the command folder The cleanup actions mostly consist of: * Replacing method comments with docstrings * Replacing BaseException with Exception * Removing db.commit when making a SELECT query There are a handful of places where I cleaned up the logic a little bit, but I didn’t do the kind of dive necessary to find all of the issues. * Update Chart.yaml Co-authored-by: Jpop Wilson <[email protected]>
1 parent d9a9ff5 commit ee1b87b

27 files changed

+199
-199
lines changed

charts/agimus/Chart.yaml

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,5 @@ apiVersion: v2
22
name: agimus
33
description: A helm chart for a discord bot that also runs a mysql db
44
type: application
5-
version: v1.4.1
6-
appVersion: v1.4.1
5+
version: v1.4.11
6+
appVersion: v1.4.11

commands/agimus.py

+14-16
Original file line numberDiff line numberDiff line change
@@ -24,26 +24,26 @@ async def agimus(message:discord.Message):
2424
agimus_channel = await message.guild.fetch_channel(agimus_channel_id)
2525

2626
completion_text = handle_special_questions(question)
27-
if completion_text == None:
27+
if completion_text is None:
2828
completion_text = handle_openai_query(question)
2929

30-
random_footer_texts = [
31-
f"Feel free to continue our conversation there!",
32-
f"See you down there!",
33-
f"Can't wait 'til you see what I said!",
34-
f"Don't want everyone here to know our secret plans...",
35-
f"SECRETS",
36-
f"It's more fun this way",
37-
f"LOBE ENLARGEMENT heh heh heh..."
38-
]
3930
if message.channel.id != agimus_channel_id:
40-
4131
agimus_response_message = await agimus_channel.send(embed=discord.Embed(
4232
title="To \"answer\" your question...",
4333
description=f"{message.author.mention} asked:\n\n> {message.content}\n\n**Answer:** {completion_text}",
4434
color=discord.Color.random()
4535
).set_footer(text="Response generated via AI Algorithms. This does not constitute legal, medical or financial advice. You are talking to a robot."))
4636

37+
random_footer_texts = [
38+
"Feel free to continue our conversation there!",
39+
"See you down there!",
40+
"Can't wait 'til you see what I said!",
41+
"Don't want everyone here to know our secret plans...",
42+
"SECRETS",
43+
"It's more fun this way",
44+
"LOBE ENLARGEMENT heh heh heh..."
45+
]
46+
4747
await message.reply(embed=discord.Embed(
4848
title=f"Redirecting...",
4949
description=f"Find your response here: {agimus_response_message.jump_url}.",
@@ -76,13 +76,11 @@ def handle_special_questions(question):
7676
"do you know where you are": "I am in a dream."
7777
}
7878

79-
completion_text = None
8079
for key in special_questions.keys():
8180
if key in question:
82-
completion_text = special_questions[key]
83-
break
84-
85-
return completion_text
81+
return special_questions[key]
82+
83+
return None
8684

8785
def handle_openai_query(question):
8886
prompt_start = "You are a mischievous computer intelligence named AGIMUS. You are a bot on a Discord server called The USS Hood for fans of The Greatest Generation and The Greatest Discovery Star Trek podcasts, hosted by Ben Ahr Harrison and Adam Pranica. The Fans are called The Friends of DeSoto. You cannot self-destruct the ship. You live on a bookshelf in jp00p's house. You are a little bit embarrassed to exist. You are evil but with a heart of gold. Your voice sounds like Jeffrey Combs. Answer the following prompt"

commands/badges.py

+9-17
Original file line numberDiff line numberDiff line change
@@ -312,12 +312,14 @@ async def sets(ctx:discord.ApplicationContext, public:str, category:str, selecti
312312
await ctx.followup.send(files=chunk, ephemeral=not public)
313313

314314

315-
# slash command to get common badge stats
316315
@badge_group.command(
317316
name="statistics",
318317
description="See the server-wide badge statistics"
319318
)
320319
async def badge_statistics(ctx:discord.ApplicationContext):
320+
"""
321+
slash command to get common badge stats
322+
"""
321323
results = {}
322324
results = run_badge_stats_queries()
323325
top_collectors = [res for res in results["top_collectors"]]
@@ -349,8 +351,10 @@ async def badge_statistics(ctx:discord.ApplicationContext):
349351
description="Which user to gift the badge to",
350352
required=True
351353
)
352-
# give a random badge to a user
353354
async def gift_badge(ctx:discord.ApplicationContext, user:discord.User):
355+
"""
356+
give a random badge to a user
357+
"""
354358
notification_channel_id = get_channel_id(config["handlers"]["xp"]["notification_channel"])
355359
logger.info(f"{ctx.author.display_name} is attempting to {Style.BRIGHT}gift a random badge{Style.RESET_ALL} to {user.display_name}")
356360

@@ -389,8 +393,10 @@ async def gift_badge_error(ctx, error):
389393
required=True,
390394
autocomplete=all_badges_autocomplete
391395
)
392-
# give a random badge to a user
393396
async def gift_specific_badge(ctx:discord.ApplicationContext, user:discord.User, specific_badge:str):
397+
"""
398+
give a random badge to a user
399+
"""
394400
notification_channel_id = get_channel_id(config["handlers"]["xp"]["notification_channel"])
395401
logger.info(f"{ctx.author.display_name} is attempting to {Style.BRIGHT}gift {specific_badge}{Style.RESET_ALL} to {user.display_name}")
396402

@@ -457,7 +463,6 @@ def db_get_all_affiliations():
457463
sql = "SELECT distinct(affiliation_name) FROM badge_affiliation"
458464
query.execute(sql)
459465
rows = query.fetchall()
460-
db.commit()
461466
query.close()
462467
db.close()
463468

@@ -478,7 +483,6 @@ def db_get_all_affiliation_badges(affiliation):
478483
vals = (affiliation,)
479484
query.execute(sql, vals)
480485
rows = query.fetchall()
481-
db.commit()
482486
query.close()
483487
db.close()
484488

@@ -502,7 +506,6 @@ def db_get_badges_user_has_from_affiliation(user_id, affiliation):
502506
vals = (user_id, affiliation)
503507
query.execute(sql, vals)
504508
rows = query.fetchall()
505-
db.commit()
506509
query.close()
507510
db.close()
508511

@@ -518,7 +521,6 @@ def db_get_all_franchises():
518521
sql = "SELECT distinct(franchise) FROM badge_info"
519522
query.execute(sql)
520523
rows = query.fetchall()
521-
db.commit()
522524
query.close()
523525
db.close()
524526

@@ -537,7 +539,6 @@ def db_get_all_franchise_badges(franchise):
537539
vals = (franchise,)
538540
query.execute(sql, vals)
539541
rows = query.fetchall()
540-
db.commit()
541542
query.close()
542543
db.close()
543544

@@ -559,7 +560,6 @@ def db_get_badges_user_has_from_franchise(user_id, franchise):
559560
vals = (user_id, franchise)
560561
query.execute(sql, vals)
561562
rows = query.fetchall()
562-
db.commit()
563563
query.close()
564564
db.close()
565565

@@ -575,7 +575,6 @@ def db_get_all_time_periods():
575575
sql = "SELECT distinct(time_period) FROM badge_info"
576576
query.execute(sql)
577577
rows = query.fetchall()
578-
db.commit()
579578
query.close()
580579
db.close()
581580

@@ -602,7 +601,6 @@ def db_get_all_time_period_badges(time_period):
602601
vals = (time_period,)
603602
query.execute(sql, vals)
604603
rows = query.fetchall()
605-
db.commit()
606604
query.close()
607605
db.close()
608606

@@ -624,7 +622,6 @@ def db_get_badges_user_has_from_time_period(user_id, time_period):
624622
vals = (user_id, time_period)
625623
query.execute(sql, vals)
626624
rows = query.fetchall()
627-
db.commit()
628625
query.close()
629626
db.close()
630627

@@ -640,7 +637,6 @@ def db_get_all_types():
640637
sql = "SELECT distinct(type_name) FROM badge_type"
641638
query.execute(sql)
642639
rows = query.fetchall()
643-
db.commit()
644640
query.close()
645641
db.close()
646642

@@ -661,7 +657,6 @@ def db_get_all_type_badges(type):
661657
vals = (type,)
662658
query.execute(sql, vals)
663659
rows = query.fetchall()
664-
db.commit()
665660
query.close()
666661
db.close()
667662

@@ -685,7 +680,6 @@ def db_get_badges_user_has_from_type(user_id, type):
685680
vals = (user_id, type)
686681
query.execute(sql, vals)
687682
rows = query.fetchall()
688-
db.commit()
689683
query.close()
690684
db.close()
691685

@@ -738,7 +732,6 @@ def get_user_badges(user_discord_id:int):
738732
vals = (user_discord_id,)
739733
query.execute(sql, vals)
740734
badges = [badge[0] for badge in query.fetchall()]
741-
db.commit()
742735
query.close()
743736
db.close()
744737
return badges
@@ -756,7 +749,6 @@ def run_badge_stats_queries():
756749
query = db.cursor(dictionary=True)
757750
query.execute(sql)
758751
results[name] = query.fetchall()
759-
db.commit()
760752
query.close()
761753
db.close()
762754
return results

commands/clear_media.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -8,22 +8,22 @@
88
# Path to base bot directory
99
base_path = Path(__file__).parent.parent
1010

11-
# clear_media() - Entrypoint for !clear_media
12-
# message[required]: discord.Message
13-
# This function is the main entrypoint of the !clear_media command
14-
# This will remove all .mp4 files from the data/clips and data/drops directories
15-
# and allow the bot to re-load them as needed. Useful for debugging.
1611
@bot.command()
1712
@commands.check(access_check)
1813
async def clear_media(ctx):
14+
"""
15+
This function is the main entrypoint of the !clear_media command
16+
This will remove all .mp4 files from the data/clips and data/drops directories
17+
and allow the bot to re-load them as needed. Useful for debugging.
18+
"""
1919
drop_files = glob(os.path.join(base_path, 'data/drops/', '*.mp4'))
2020
clip_files = glob(os.path.join(base_path, 'data/clips/', '*.mp4'))
2121

2222
errors = []
2323
for file_path in [*drop_files, *clip_files]:
2424
try:
2525
os.remove(file_path)
26-
except:
26+
except Exception:
2727
logger.debug(f"{Fore.RED}ERROR: Unable to remove file: {file_path}{Fore.RESET}")
2828
errors.append(file_path)
2929

commands/clip.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ async def clips_list(ctx:discord.ApplicationContext):
4242
try:
4343
await ctx.author.send(embed=embed)
4444
await ctx.respond(f"{get_emoji('tendi_smile_happy')} Sent you a DM with the full List of Clips!", ephemeral=True)
45-
except:
45+
except Exception:
4646
await ctx.respond(embed=embed, ephemeral=True)
4747
else:
4848
await ctx.respond(embed=embed, ephemeral=True)
@@ -85,7 +85,7 @@ async def clip_post(ctx:discord.ApplicationContext, query:str, private:bool):
8585
await ctx.respond(file=discord.File(filename), ephemeral=private)
8686
if not private:
8787
set_timekeeper(ctx)
88-
except BaseException as err:
88+
except Exception as err:
8989
logger.info(f"{Fore.RED}ERROR LOADING CLIP: {err}{Fore.RESET}")
9090
else:
9191
await ctx.respond(f"{get_emoji('ezri_frown_sad')} Clip not found! To get a list of clips run: /clips list", ephemeral=True)

commands/computer.py

+10-9
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,16 @@ def get_random_title():
145145
]
146146
return random.choice(titles)
147147

148-
# We may want to catch a couple questions with Ship Computer-specific answers.
149-
# Rather than trying to parse the question for these, we can catch the specific
150-
# answer that is returned by WA and infer that it should have a different answer instead.
151-
#
152-
# e.g. "Who are you?" and "What is your name?" both return "My name is Wolfram|Alpha."
153-
# so we only need to catch that answer versus trying to figure out all permutations that
154-
# would prompt it.
155148
def catch_special_case_responses(answer):
149+
"""
150+
We may want to catch a couple questions with Ship Computer-specific answers.
151+
Rather than trying to parse the question for these, we can catch the specific
152+
answer that is returned by WA and infer that it should have a different answer instead.
153+
154+
e.g. "Who are you?" and "What is your name?" both return "My name is Wolfram|Alpha."
155+
so we only need to catch that answer versus trying to figure out all permutations that
156+
would prompt it.
157+
"""
156158
special_cases = {
157159
"My name is Wolfram|Alpha.": "I am The USS Hood Main Library Computer.",
158160
"I was created by Stephen Wolfram and his team.": "I was designed by various data cybernetic scientists at The Daystrom Institute.",
@@ -164,7 +166,6 @@ def catch_special_case_responses(answer):
164166

165167
for key in special_cases.keys():
166168
if key in answer:
167-
answer = special_cases[key]
168-
break
169+
return special_cases[key]
169170

170171
return answer

commands/drop.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,15 @@ async def drop_autocomplete(ctx:discord.AutocompleteContext):
2323
# Create drop Slash Command Group
2424
drop = bot.create_group("drop", "Drop Commands!")
2525

26-
# drop_list() - Entrypoint for `/drops list`` command
27-
# List the available drops by key and send to user as ephemeral
2826
@drop.command(
2927
name="list",
3028
description="Retrieve the List of Drops"
3129
)
3230
async def drop_list(ctx:discord.ApplicationContext):
31+
"""
32+
Entrypoint for `/drops list`` command
33+
List the available drops by key and send to user as ephemeral
34+
"""
3335
logger.info(f"{Fore.RED}Firing `/drop list` command, requested by {ctx.author.name}!{Fore.RESET}")
3436
drops_list = "\n".join(drop_data)
3537
embed = discord.Embed(
@@ -47,10 +49,6 @@ async def drop_list(ctx:discord.ApplicationContext):
4749
else:
4850
await ctx.respond(embed=embed, ephemeral=True)
4951

50-
# drop_post() - Entrypoint for `/drops post` command
51-
# Parses a query, determines if it's allowed in the channel,
52-
# and if allowed retrieve from metadata to do matching and
53-
# then send the .mp4 file
5452
@drop.command(
5553
name="post",
5654
description="Send a drop to the channel or to just yourself via the <private> option",
@@ -68,6 +66,12 @@ async def drop_list(ctx:discord.ApplicationContext):
6866
)
6967
@commands.check(access_check)
7068
async def drop_post(ctx:discord.ApplicationContext, query:str, private:bool):
69+
"""
70+
Entrypoint for `/drops post` command
71+
Parses a query, determines if it's allowed in the channel,
72+
and if allowed retrieve from metadata to do matching and
73+
then send the .mp4 file
74+
"""
7175
logger.info(f"{Fore.RED}Firing `/drop post` command, requested by {ctx.author.name}!{Fore.RESET}")
7276
# Private drops are not on the timer
7377
drop_allowed = True

commands/dustbuster.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
from common import *
22
from utils.check_channel_access import access_check
33

4-
# dustbuster() - Entrypoint for /dustbuster command
54
@bot.slash_command(
65
name="dustbuster",
76
description="Return 5 random Trek Characters as a possible Away Team"

commands/fmk.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
from common import *
22
from utils.check_channel_access import access_check
33

4-
# fmk() - Entrypoint for /fmk command
5-
# This function is the main entrypoint of the /fmk command
6-
# and will return a prompt with three random characters
74
@bot.slash_command(
85
name="fmk",
96
description="Return 3 random Trek Characters as an FMK prompt"
107
)
118
@commands.check(access_check)
129
async def fmk(ctx:discord.ApplicationContext):
10+
"""
11+
This function is the main entrypoint of the /fmk command
12+
and will return a prompt with three random characters
13+
"""
1314
f = open(config["commands"]["fmk"]["data"])
1415
fmk_characters = f.read().splitlines()
1516
f.close()

0 commit comments

Comments
 (0)