pythonbotsirctwitch

TwitchIO send cool down message


basically I'm using TwitchIO for a twitch BOT. I set a time limit to prevent users from spamming. When a user tries to spam an error is raised indicating that they must wait 30 seconds. However, I would like to send this message to the twitch chat using ctx.Send(…).

    @commands.command()
    @commands.cooldown(1,30,commands.Bucket.user)
    async def test(self, ctx: commands.Context):
        await ctx.send(f'user message from {ctx.author.name}!')

When on the twitch chat I use the !test command the message 'user message from {ctx.author.name}! The problem is that I can't re-run the command to send the error message because it is in the decorator. Here is how the cooldown decorator is organized:

def cooldown(rate, per, bucket=Bucket.default):
    def decorator(func: FN) -> FN:
        if isinstance(func, Command):
            func._cooldowns.append(Cooldown(rate, per, bucket))
        else:
            func.__cooldowns__ = [Cooldown(rate, per, bucket)]
        return func

    return decorator

    def update_bucket(self, ctx):
        now = time.time()

        self._tokens = self.get_tokens(now)

        if self._tokens == 0:
            self._window = now

        if self._tokens == self._rate:
            retry = self._per - (now - self._window)
            raise CommandOnCooldown(command=ctx.command, retry_after=retry)


        self._tokens += 1

        if self._tokens == self._rate:
            self._window = now

class CommandOnCooldown(TwitchCommandError):
    def __init__(self, command, retry_after):
        self.command = command
        self.retry_after = retry_after
        super().__init__(f"Command <{command.name}> is on cooldown. Try again in ({retry_after:.2f})s")

Do you have an idea?


Solution

  • Whenever there is an error, twitch io calls the "event_command_error". You can overwrite this by using the following code:

        async def event_command_error(self, ctx, error: Exception) -> None:
            print(error)
    

    Put this code in the same file you put your "test" command. Of course this code just prints the error, but with the ctx available, you should be able to do whatever you want. Happy hacking.