Skip to main content

advanced_cooldowns/
main.rs

1use poise::serenity_prelude as serenity;
2
3struct Data {} // User data, which is stored and accessible in all command invocations
4type Error = Box<dyn std::error::Error + Send + Sync>;
5type Context<'a> = poise::Context<'a, Data, Error>;
6
7#[poise::command(slash_command, prefix_command)]
8async fn dynamic_cooldowns(ctx: Context<'_>) -> Result<(), Error> {
9    {
10        let mut cooldown_tracker = ctx.command().cooldowns.lock().unwrap();
11
12        // You can change the cooldown duration depending on the message author, for example
13        let mut cooldown_durations = poise::CooldownConfig::default();
14        if ctx.author().id == 472029906943868929 {
15            cooldown_durations.user = Some(std::time::Duration::from_secs(10));
16        }
17
18        match cooldown_tracker.remaining_cooldown(ctx.cooldown_context(), &cooldown_durations) {
19            Some(remaining) => {
20                return Err(format!("Please wait {} seconds", remaining.as_secs()).into())
21            }
22            None => cooldown_tracker.start_cooldown(ctx.cooldown_context()),
23        }
24    };
25
26    ctx.say("You successfully invoked the command!").await?;
27    Ok(())
28}
29
30#[tokio::main]
31async fn main() {
32    let token = std::env::var("DISCORD_TOKEN").expect("missing DISCORD_TOKEN");
33    let framework = poise::Framework::builder()
34        .options(poise::FrameworkOptions {
35            commands: vec![dynamic_cooldowns()],
36            // This is important! Or else, the command will be marked as invoked before our custom
37            // cooldown code has run - even if the command ends up not running!
38            manual_cooldowns: true,
39            ..Default::default()
40        })
41        .setup(|ctx, _ready, framework| {
42            Box::pin(async move {
43                poise::builtins::register_globally(ctx, &framework.options().commands).await?;
44                Ok(Data {})
45            })
46        })
47        .build();
48
49    let client = serenity::Client::builder(token, serenity::GatewayIntents::non_privileged())
50        .framework(framework)
51        .await;
52
53    client.unwrap().start().await.unwrap();
54}