Struct serenity::cache::Cache

source ·
#[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.

This is the list of cached resources and the events that populate them:

The documentation of each event contains the required gateway intents.

Implementations§

source§

impl Cache

source

pub fn new() -> Self

Creates a new cache.

source

pub fn new_with_settings(settings: Settings) -> Self

Creates a new cache instance with settings applied.

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

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

let cache = Cache::new_with_settings(settings);
source

pub fn unknown_members(&self) -> u64

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.

struct Handler;

#[serenity::async_trait]
impl EventHandler for Handler {
    async fn cache_ready(&self, ctx: Context, _: Vec<GuildId>) {
        println!("{} unknown members", ctx.cache.unknown_members());
    }
}
source

pub fn guilds(&self) -> Vec<GuildId>

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);
    }
}
source

pub fn channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannelRef<'_>>

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

source

pub fn channel_messages( &self, channel_id: impl Into<ChannelId> ) -> Option<ChannelMessagesRef<'_>>

Get a reference to the cached messages for a channel based on the given Id.

§Examples

Find all messages by user ID 8 in channel ID 7:

let messages_in_channel = cache.channel_messages(7);
let messages_by_user = messages_in_channel
    .as_ref()
    .map(|msgs| msgs.values().filter(|m| m.author.id == 8).collect::<Vec<_>>());
source

pub fn guild<G: Into<GuildId>>(&self, id: G) -> Option<GuildRef<'_>>

Gets a reference to a guild from the cache based on the given id.

§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);
};
source

pub fn guild_count(&self) -> usize

Returns the number of cached guilds.

source

pub fn member( &self, guild_id: impl Into<GuildId>, user_id: impl Into<UserId> ) -> Option<MemberRef<'_>>

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

§Examples

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

let roles_len = {
    let channel = match cache.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;
        },
    };

    cache.member(channel.guild_id, message.author.id).map(|m| m.roles.len())
};

let message_res = if let Some(roles_len) = roles_len {
    let msg = format!("You have {} roles", roles_len);
    message.channel_id.say(&http, &msg).await
} else {
    message.channel_id.say(&http, "Error finding member data").await
};

if let Err(why) = message_res {
    println!("Error sending message: {:?}", why);
}
source

pub fn guild_roles( &self, guild_id: impl Into<GuildId> ) -> Option<GuildRolesRef<'_>>

source

pub fn unavailable_guilds(&self) -> ReadOnlyMapRef<'_, GuildId, ()>

This method clones and returns all unavailable guilds.

source

pub fn guild_channels( &self, guild_id: impl Into<GuildId> ) -> Option<GuildChannelsRef<'_>>

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

source

pub fn guild_channel_count(&self) -> usize

Returns the number of guild channels in the cache.

source

pub fn shard_count(&self) -> u32

Returns the number of shards.

source

pub fn message<C, M>( &self, channel_id: C, message_id: M ) -> Option<MessageRef<'_>>
where C: Into<ChannelId>, M: Into<MessageId>,

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."),
};
source

pub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<GuildRoleRef<'_>>
where G: Into<GuildId>, R: Into<RoleId>,

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);
};
source

pub fn settings(&self) -> SettingsRef<'_>

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);
source

pub fn set_max_messages(&self, max: usize)

Sets the maximum amount of messages per channel to cache.

By default, no messages will be cached.

source

pub fn user<U: Into<UserId>>(&self, user_id: U) -> Option<UserRef<'_>>

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);
}
source

pub fn users(&self) -> ReadOnlyMapRef<'_, UserId, User>

Clones all users and returns them.

source

pub fn user_count(&self) -> usize

Returns the amount of cached users.

source

pub fn current_user(&self) -> CurrentUserRef<'_>

This method provides a reference to the user used by the bot.

source

pub fn category(&self, channel_id: ChannelId) -> Option<GuildChannelRef<'_>>

Returns a channel category matching the given ID

source

pub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId>

Returns the parent category of the given channel ID.

source

pub fn guild_categories( &self, guild_id: GuildId ) -> Option<HashMap<ChannelId, GuildChannel>>

Clones all channel categories in the given guild and returns them.

source

pub fn update<E: CacheUpdate>(&self, e: &mut E) -> Option<E::Output>

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§

source§

impl AsRef<Cache> for (&Arc<Cache>, &Http)

Available on crate feature http only.
source§

fn as_ref(&self) -> &Cache

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

impl AsRef<Cache> for Arc<Context>

Available on crate feature client only.
source§

fn as_ref(&self) -> &Cache

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

impl AsRef<Cache> for Cache

Available on crate feature client only.
source§

fn as_ref(&self) -> &Cache

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

impl AsRef<Cache> for Context

Available on crate feature client only.
source§

fn as_ref(&self) -> &Cache

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

impl Debug for Cache

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for Cache

source§

fn default() -> Self

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

Auto Trait Implementations§

§

impl !RefUnwindSafe for Cache

§

impl Send for Cache

§

impl Sync for Cache

§

impl Unpin for Cache

§

impl UnwindSafe for Cache

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

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

fn in_current_span(self) -> Instrumented<Self>

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

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

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

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

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

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> DebuggableStorage for T
where T: Any + Send + Sync + Debug,