adampy / adambot

General-purpose discord bot, called Adam-Bot. The main bot instance is hosted on AWS EC2 Spot Instances, however can run locally when needed.
6 stars 6 forks source link

Repetitive code using `get_context_type` #46

Open adampy opened 2 years ago

adampy commented 2 years ago

I noticed that in command handlers, after a call to self.bot.get_context_type, a new variable called author is defined depending on the return type of the former call. I propose making a new function called unbox_context which is essentially self.bot.get_context_type but with an additional code to grab the author.

Proposed unbox_content method that is linked to AdamBot as get_context_type is...

def unbox_context(ctx: commands.Context | discord.Interaction) -> Tuple[ContextTypes, discord.User | bool]:
    if issubclass(ctx.__class__, commands.Context):
        return ContextTypes.Context, ctx.author
    elif issubclass(ctx.__class__, discord.Interaction):
        return ContextTypes.Interaction, ctx.user
    return ContextTypes.Unknown, False

Then instead of doing...

ctx_type = self.bot.get_context_type(ctx)
if ctx_type == self.ContextTypes.Unknown:
    return
if ctx_type == self.ContextTypes.Context:
    author = ctx.author
else:
    author = ctx.user

we could have...

ctx_type, author = self.bot.unbox_context(ctx)
if not author:
    return

or even...

ctx_type, author = self.bot.unbox_context(ctx)
if ctx_type == self.ContextTypes.Unknown:
    return
raven0034 commented 2 years ago

this is definitely something i was slightly concerned about but i wasn't entirely sure on the best way to fully tidy it up - your idea looks cool if you can make it work it would certainly help to tidy up the code