pythondiscorddiscord.py

Custom wraps on discord command


I created a custom wraps like this

def addLogger(fn):
    from functools import wraps
    @wraps(fn)
    async def add_logger(*args, **kwargs):
        print(f"addLogger: About to run {fn.__name__}") 
        log = logger
        startTime = time.time()
        log.info('About to run %s' % fn.__name__)
        result = await fn(*args, **kwargs)
        log.info('Done running %s Execution time: %s' % (fn.__name__, time.time() - startTime))
        print(f"addLogger: Done running {fn.__name__}")  
        return result 
    return add_logger

and it's working great on this function

@bot.event
@addLogger
async def on_ready():
    logger.info(f'{bot.user.name} has connected to Discord!')
    try : 
        synced = await bot.tree.sync()
        print(f"Synced {len(synced)} command")
    except Exception as e:
        print(e)

but not on list_cogs its just does nothing

@addLogger
@bot.tree.command(name="list_cogs", description="list all cogs")
async def list_cogs(interaction):
    
        await interaction.response.send_message(f"{cogList}")

I already tried to return commands.check(add_logger) instead of add_logger but it ends up to not work at all


Solution

  • You need to have @addLogger after the @bot.tree.command() line. So the correct code would be

    @bot.tree.command(name="list_cogs", description="list all cogs")
    @addLogger
    async def list_cogs(interaction):
        await interaction.response.send_message(f"{cogList}")
    

    Think of it like @addLogger changing the code of list_cogs() so the new list_cogs() function will do what it did before, but also time itself. Then, once you have that new function, that's what you add to the bot tree as a command.