Discord.py Bot Custom Checks With Slash Commands (app_commands) - passing multiple arguments

for the record i cant find anything online or come up with anything so im asking here

Question:
So, as shown in the code snipet below, in script 2 i have a function that checks if a person has a role (i know the app_command module has that built in, this is a proof of concept). And that function need the interaction, not a problem that is allready passed automaticaly, but how would it be possible to pass more than one argument through the app_commads.check (or any other way to have the same result) into the provided function? Also idealy avoid something like and if check in the main command body for this, i want to be able to tell the difference between permision checks and the command code.

Script snipets:
script 1 snipet ▼

@app_commands.guild_only()
class CommandGroup(app_commands.Group):
  @app_commands.command()
  @app_commands.check(SCRIPT_2.hasRlRank,3)
  async def list(self,intr : discord.Interaction):
    #do stuff, not a problem

script 2 snipet ▼

def hasRlRank(intr:discord.Interaction,roleCodename:str):
  # do stuff and return results, not a problem
  return var

Did you tried use Partial Functions?

There is a thing is Python called functools.partial which you can create a version of your check function that has some of its arguments pre-filled. I think you can pass the extra arguments ahead of time, and only the interaction remains to be provided during the actual check.

Which can be something like this:

from functools import partial

@app_commands.guild_only()
class CommandGroup(app_commands.Group):
    @app_commands.command()
    @app_commands.check(partial(SCRIPT_2.hasRlRank, roleCodename="3"))
    async def list(self, intr: discord.Interaction):
        # do stuff, not a problem

You can see more here: functools — Higher-order functions and operations on callable objects — Python 3.12.1 documentation

1 Like

i will try it later and tell you if it worked, seems like it should tho, i didnt know about the partial thing, thanks

1 Like

Have you tried using tree_commands? they work for me…

what exactly do you mean by tree_commands?.. well one of us didnt understand because the code snipet above is just the command group, it is added to the tree below ofcourse (and then synced with discord)

in the same script as the command group ▼

async def setup(bot):
  bot.tree.add_command(CommandGroup(name="settings"))

in the main file ▼

for cmd_file in cmd_dir.glob("*.py"):
  if cmd_file.name != "__init__.py":
    await bot.load_extension(f"cmds.{cmd_file.name[:-3]}")
await bot.tree.sync()

but im not asking how to do that

it did indeed work, thanks, im going to mark it as the solution

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.