#[non_exhaustive]
pub struct Cache { /* private fields */ }
Available on crate feature cache only.
Expand description

A cache containing data received from Shards.

Using the cache allows to avoid REST API requests via the http module where possible. Issuing too many requests will lead to ratelimits.

The cache will clone all values when calling its methods.

Implementations

Creates a new cache.

Creates a new cache instance with settings applied.

Examples
use serenity::cache::{Cache, Settings};

let mut settings = Settings::new();
settings.max_messages(10);

let cache = Cache::new_with_settings(settings);

Fetches the number of Members that have not had data received.

The important detail to note here is that this is the number of _member_s that have not had data received. A single User may have multiple associated member objects that have not been received.

This can be used in combination with Shard::chunk_guild, and can be used to determine how many members have not yet been received.

use std::thread;
use std::time::Duration;

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn ready(&self, ctx: Context, _: Ready) {
        // Wait some time for guilds to be received.
        //
        // You should keep track of this in a better fashion by tracking how
        // many guilds each `ready` has, and incrementing a counter on
        // GUILD_CREATEs. Once the number is equal, print the number of
        // unknown members.
        //
        // For demonstrative purposes we're just sleeping the thread for 5
        // seconds.
        tokio::time::sleep(Duration::from_secs(5)).await;

        println!("{} unknown members", ctx.cache.unknown_members());
    }
}

let mut client =
    Client::builder("token", GatewayIntents::default()).event_handler(Handler).await?;

client.start().await?;

Fetches a vector of all PrivateChannel Ids that are stored in the cache.

Examples

If there are 6 private channels and 2 groups in the cache, then 8 Ids will be returned.

Printing the count of all private channels and groups:

let amount = cache.private_channels().len();

println!("There are {} private channels", amount);

Fetches a vector of all Guilds’ Ids that are stored in the cache.

Note that if you are utilizing multiple Shards, then the guilds retrieved over all shards are included in this count – not just the current Context’s shard, if accessing from one.

Examples

Print all of the Ids of guilds in the Cache:

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn ready(&self, context: Context, _: Ready) {
        let guilds = context.cache.guilds().len();

        println!("Guilds in the Cache: {}", guilds);
    }
}

Retrieves a Channel from the cache based on the given Id.

This will search the channels map, then the Self::private_channels map.

If you know what type of channel you’re looking for, you should instead manually retrieve from one of the respective methods:

This method allows to extract specific data from the cached messages of a channel by providing a selector closure picking what you want to extract from the messages iterator of a given channel.

// Find all messages by user ID 8 in channel ID 7
let messages_by_user = cache.channel_messages_field(7, |msgs| {
    msgs.filter_map(|m| if m.author.id == 8 { Some(m.clone()) } else { None })
        .collect::<Vec<_>>()
});

Clones an entire guild from the cache based on the given id.

In order to clone only a field of the guild, use Self::guild_field.

Examples

Retrieve a guild from the cache and print its name:

// assuming the cache is in scope, e.g. via `Context`
if let Some(guild) = cache.guild(7) {
    println!("Guild name: {}", guild.name);
}

This method allows to select a field of the guild instead of the entire guild by providing a field_selector-closure picking what you want to clone.

// We clone only the `len()` returned `usize` instead of the entire guild or the channels.
if let Some(channel_len) = cache.guild_field(7, |guild| guild.channels.len()) {
    println!("Guild channels count: {}", channel_len);
}

Returns the number of cached guilds.

Retrieves a reference to a Guild’s channel. Unlike Self::channel, this will only search guilds for the given channel.

The only advantage of this method is that you can pass in anything that is indirectly a ChannelId.

Examples

Getting a guild’s channel via the Id of the message received through a EventHandler::message event dispatch:

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn message(&self, context: Context, message: Message) {
        let channel = match context.cache.guild_channel(message.channel_id) {
            Some(channel) => channel,
            None => {
                let result = message
                    .channel_id
                    .say(&context, "Could not find guild's channel data")
                    .await;
                if let Err(why) = result {
                    println!("Error sending message: {:?}", why);
                }

                return;
            },
        };
    }
}

let mut client =
    Client::builder("token", GatewayIntents::default()).event_handler(Handler).await?;

client.start().await?;

This method allows to only clone a field of the guild channel instead of the entire guild by providing a field_selector-closure picking what you want to clone.

// We clone only the `name` instead of the entire channel.
if let Some(channel_name) = cache.guild_channel_field(7, |channel| channel.name.clone()) {
    println!("Guild channel name: {}", channel_name);
}

Retrieves a Guild’s member from the cache based on the guild’s and user’s given Ids.

Note: This will clone the entire member. Instead, retrieve the guild and retrieve from the guild’s members map to avoid this.

Examples

Retrieving the member object of the user that posted a message, in a EventHandler::message context:

let member = {
    let channel = match cache.guild_channel(message.channel_id) {
        Some(channel) => channel,
        None => {
            if let Err(why) = message.channel_id.say(http, "Error finding channel data").await {
                println!("Error sending message: {:?}", why);
            }
            return;
        },
    };

    match cache.member(channel.guild_id, message.author.id) {
        Some(member) => member,
        None => {
            if let Err(why) = message.channel_id.say(&http, "Error finding member data").await {
                println!("Error sending message: {:?}", why);
            }
            return;
        },
    }
};

let msg = format!("You have {} roles", member.roles.len());

if let Err(why) = message.channel_id.say(&http, &msg).await {
    println!("Error sending message: {:?}", why);
}

This method allows to only clone a field of a member instead of the entire member by providing a field_selector-closure picking what you want to clone.

// We clone only the `name` instead of the entire channel.
if let Some(Some(nick)) = cache.member_field(7, 8, |member| member.nick.clone()) {
    println!("Member's nick: {}", nick);
}

This method clones and returns all unavailable guilds.

This method returns all channels from a guild of with the given guild_id.

Returns the number of guild channels in the cache.

This method returns all categories from a guild of with the given guild_id.

Returns the number of shards.

Retrieves a Channel’s message from the cache based on the channel’s and message’s given Ids.

Note: This will clone the entire message.

Examples

Retrieving the message object from a channel, in a EventHandler::message context:

match cache.message(message.channel_id, message.id) {
    Some(m) => assert_eq!(message.content, m.content),
    None => println!("No message found in cache."),
};

Retrieves a PrivateChannel from the cache’s Self::private_channels map, if it exists.

The only advantage of this method is that you can pass in anything that is indirectly a ChannelId.

Examples

Retrieve a private channel from the cache and print its recipient’s name:

// assuming the cache has been unlocked

if let Some(channel) = cache.private_channel(7) {
    println!("The recipient is {}", channel.recipient);
}

Retrieves a Guild’s role by their Ids.

Note: This will clone the entire role. Instead, retrieve the guild and retrieve from the guild’s roles map to avoid this.

Examples

Retrieve a role from the cache and print its name:

// assuming the cache is in scope, e.g. via `Context`
if let Some(role) = cache.role(7, 77) {
    println!("Role with Id 77 is called {}", role.name);
}

Returns the settings.

Examples

Printing the maximum number of messages in a channel to be cached:

use serenity::cache::Cache;

let mut cache = Cache::new();
println!("Max settings: {}", cache.settings().max_messages);

Sets the maximum amount of messages per channel to cache.

By default, no messages will be cached.

Retrieves a User from the cache’s Self::users map, if it exists.

The only advantage of this method is that you can pass in anything that is indirectly a UserId.

Examples

Retrieve a user from the cache and print their name:

if let Some(user) = context.cache.user(7) {
    println!("User with Id 7 is currently named {}", user.name);
}

Clones all users and returns them.

Returns the amount of cached users.

Clones a category matching the channel_id and returns it.

Clones all categories and returns them.

Returns the amount of cached categories.

Returns the optional category ID of a channel.

This method clones and returns the user used by the bot.

This method returns the bot’s ID.

This method allows to only clone a field of the current user instead of the entire user by providing a field_selector-closure picking what you want to clone.

// We clone only the `name` instead of the entire channel.
let id = cache.current_user_field(|user| user.id);
println!("Current user's ID: {}", id);

Updates the cache with the update implementation for an event or other custom update implementation.

Refer to the documentation for CacheUpdate for more information.

Examples

Refer to the CacheUpdate examples.

Trait Implementations

Converts this type into a shared reference of the (usually inferred) input type.

Converts this type into a shared reference of the (usually inferred) input type.

Converts this type into a shared reference of the (usually inferred) input type.

Converts this type into a shared reference of the (usually inferred) input type.

Formats the value using the given formatter. Read more

Returns the “default value” for a type. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more

Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more