Expand description

Twilight Bucket

A utility crate to limit users’ usage, a third party crate of the Twilight ecosystem

All the functionality of this crate is under Bucket, see its documentation for usage info

This crate can be used with any library, but it shares Twilight’s non-goals, such as trying to be more verbose and less opinionated and Serenity already has a bucket implementation

Example

use std::{num::NonZeroU64, time::Duration};

use twilight_bucket::{Bucket, Limit};

#[tokio::main]
async fn main() {
    // A user can use it once every 10 seconds
    let my_command_user_bucket = Bucket::new(Limit::new(Duration::from_secs(10), 1));
    // It can be used up to 5 times every 30 seconds in one channel
    let my_command_channel_bucket = Bucket::new(Limit::new(Duration::from_secs(30), 5));
    run_my_command(
        my_command_user_bucket,
        my_command_channel_bucket,
        12345,
        123,
    )
    .await;
}

async fn run_my_command(
    user_bucket: Bucket,
    channel_bucket: Bucket,
    user_id: u64,
    channel_id: u64,
) -> String {
    if let Some(channel_limit_duration) = channel_bucket.limit_duration(channel_id) {
        return format!(
            "This was used too much in this channel, please wait {} seconds",
            channel_limit_duration.as_secs()
        );
    }
    if let Some(user_limit_duration) = user_bucket.limit_duration(user_id) {
        if Duration::from_secs(5) > user_limit_duration {
            tokio::time::sleep(user_limit_duration).await;
        } else {
            return format!(
                "You've been using this too much, please wait {} seconds",
                user_limit_duration.as_secs()
            );
        }
    }
    user_bucket.register(user_id);
    channel_bucket.register(channel_id);
    "Ran your command".to_owned()
}

Structs

This is the main struct to do everything you need

Information about how often something is able to be used