Cooldowns
Demonstrates two ways to apply a rate limit to a command, and how to handle the CooldownError when the limit is exceeded.
from matrix import Bot, Context, cooldown
from matrix.errors import CooldownError
bot = Bot()
# Invoke by using !hello
@cooldown(rate=2, period=10)
@bot.command("hello")
async def hello_command(ctx: Context) -> None:
await ctx.reply("Hello World.")
@hello_command.error(CooldownError)
async def hello_command_error_handler(ctx: Context, error: CooldownError) -> None:
await ctx.reply(f"⏳ Try again in {error.retry:.1f}s")
# Invoke by using !cooldown_command
@bot.command(cooldown=(1, 10))
async def cooldown_command(ctx: Context) -> None:
await ctx.reply("This is limited to 1 uses per 10s per user.")
@cooldown_command.error(CooldownError)
async def cooldown_function(ctx: Context, error: CooldownError) -> None:
await ctx.reply(f"⏳ Try again in {error.retry:.1f}s")
bot.start(config="config.yaml")
There are two ways to set a cooldown:
@cooldown(rate, period)decorator — applied before@bot.command.rate=2, period=10means 2 uses per 10 seconds per user.cooldown=(rate, period)argument — passed directly to@bot.commandfor a more compact one-liner.
Both produce a CooldownError when the limit is exceeded. The error object exposes error.retry — the number of seconds until the user can try again — which you can surface in the reply.