#[non_exhaustive]pub struct Cache { /* private fields */ }
Expand description
A cache containing data received from Shard
s.
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:
- channels:
ChannelCreateEvent
,ChannelUpdateEvent
,GuildCreateEvent
- guilds:
GuildCreateEvent
- unavailable_guilds:
ReadyEvent
,GuildDeleteEvent
- users:
GuildMemberAddEvent
,GuildMemberRemoveEvent
,GuildMembersChunkEvent
,PresenceUpdateEvent
,ReadyEvent
- presences:
PresenceUpdateEvent
,ReadyEvent
- messages:
MessageCreateEvent
The documentation of each event contains the required gateway intents.
Implementations§
Source§impl Cache
impl Cache
Sourcepub fn new_with_settings(settings: Settings) -> Self
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);
Sourcepub fn unknown_members(&self) -> u64
pub fn unknown_members(&self) -> u64
Fetches the number of Member
s 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());
}
}
Sourcepub fn guilds(&self) -> Vec<GuildId>
pub fn guilds(&self) -> Vec<GuildId>
Fetches a vector of all Guild
s’ Ids that are stored in the cache.
Note that if you are utilizing multiple Shard
s, 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);
}
}
Sourcepub fn channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannelRef<'_>>
👎Deprecated: Use Cache::guild and Guild::channels instead
pub fn channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannelRef<'_>>
Retrieves a GuildChannel
from the cache based on the given Id.
Sourcepub fn channel_messages(
&self,
channel_id: impl Into<ChannelId>,
) -> Option<ChannelMessagesRef<'_>>
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<_>>());
Sourcepub fn guild<G: Into<GuildId>>(&self, id: G) -> Option<GuildRef<'_>>
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);
};
Sourcepub fn guild_count(&self) -> usize
pub fn guild_count(&self) -> usize
Returns the number of cached guilds.
Sourcepub fn member(
&self,
guild_id: impl Into<GuildId>,
user_id: impl Into<UserId>,
) -> Option<MemberRef<'_>>
👎Deprecated: Use Cache::guild and Guild::members instead
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);
}
pub fn guild_roles( &self, guild_id: impl Into<GuildId>, ) -> Option<GuildRolesRef<'_>>
This method clones and returns all unavailable guilds.
Sourcepub fn guild_channels(
&self,
guild_id: impl Into<GuildId>,
) -> Option<GuildChannelsRef<'_>>
👎Deprecated: Use Cache::guild and Guild::channels instead
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
.
Sourcepub fn guild_channel_count(&self) -> usize
pub fn guild_channel_count(&self) -> usize
Returns the number of guild channels in the cache.
Sourcepub fn shard_count(&self) -> u32
pub fn shard_count(&self) -> u32
Returns the number of shards.
Sourcepub fn message<C, M>(
&self,
channel_id: C,
message_id: M,
) -> Option<MessageRef<'_>>
pub fn message<C, M>( &self, channel_id: C, message_id: M, ) -> Option<MessageRef<'_>>
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."),
};
Sourcepub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<GuildRoleRef<'_>>
👎Deprecated: Use Cache::guild and Guild::roles instead
pub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<GuildRoleRef<'_>>
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);
};
Sourcepub fn settings(&self) -> SettingsRef<'_>
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);
Sourcepub fn set_max_messages(&self, max: usize)
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.
Sourcepub fn user<U: Into<UserId>>(&self, user_id: U) -> Option<UserRef<'_>>
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);
}
Sourcepub fn user_count(&self) -> usize
pub fn user_count(&self) -> usize
Returns the amount of cached users.
Sourcepub fn current_user(&self) -> CurrentUserRef<'_>
pub fn current_user(&self) -> CurrentUserRef<'_>
This method provides a reference to the user used by the bot.
Sourcepub fn category(&self, channel_id: ChannelId) -> Option<GuildChannelRef<'_>>
👎Deprecated: Use Cache::guild, Guild::channels, and GuildChannel::kind
pub fn category(&self, channel_id: ChannelId) -> Option<GuildChannelRef<'_>>
Returns a channel category matching the given ID
Sourcepub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId>
👎Deprecated: Use Cache::guild, Guild::channels, and GuildChannel::parent_id
pub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId>
Returns the parent category of the given channel ID.
Sourcepub fn guild_categories(
&self,
guild_id: GuildId,
) -> Option<HashMap<ChannelId, GuildChannel>>
pub fn guild_categories( &self, guild_id: GuildId, ) -> Option<HashMap<ChannelId, GuildChannel>>
Clones all channel categories in the given guild and returns them.
Sourcepub fn update<E: CacheUpdate>(&self, e: &mut E) -> Option<E::Output>
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.