#[non_exhaustive]pub struct Cache { /* private fields */ }
cache
only.Expand description
Implementations
sourceimpl 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::new();
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.
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?;
sourcepub fn private_channels(&self) -> DashMap<ChannelId, PrivateChannel>
pub fn private_channels(&self) -> DashMap<ChannelId, PrivateChannel>
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);
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<Channel>
pub fn channel<C: Into<ChannelId>>(&self, id: C) -> Option<Channel>
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:
sourcepub fn channel_messages_field<T>(
&self,
channel_id: impl Into<ChannelId>,
selector: impl FnOnce(MessageIterator<'_, RandomState>) -> T
) -> Option<T>
pub fn channel_messages_field<T>(
&self,
channel_id: impl Into<ChannelId>,
selector: impl FnOnce(MessageIterator<'_, RandomState>) -> T
) -> Option<T>
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<_>>()
});
sourcepub fn guild<G: Into<GuildId>>(&self, id: G) -> Option<Guild>
pub fn guild<G: Into<GuildId>>(&self, id: G) -> Option<Guild>
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);
}
sourcepub fn guild_field<Ret, Fun>(
&self,
id: impl Into<GuildId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&Guild) -> Ret,
pub fn guild_field<Ret, Fun>(
&self,
id: impl Into<GuildId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&Guild) -> Ret,
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);
}
sourcepub fn guild_count(&self) -> usize
pub fn guild_count(&self) -> usize
Returns the number of cached guilds.
sourcepub fn guild_channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannel>
pub fn guild_channel<C: Into<ChannelId>>(&self, id: C) -> Option<GuildChannel>
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?;
sourcepub fn guild_channel_field<Ret, Fun>(
&self,
id: impl Into<ChannelId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&GuildChannel) -> Ret,
pub fn guild_channel_field<Ret, Fun>(
&self,
id: impl Into<ChannelId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&GuildChannel) -> Ret,
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);
}
sourcepub fn member<G, U>(&self, guild_id: G, user_id: U) -> Option<Member> where
G: Into<GuildId>,
U: Into<UserId>,
pub fn member<G, U>(&self, guild_id: G, user_id: U) -> Option<Member> where
G: Into<GuildId>,
U: Into<UserId>,
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);
}
sourcepub fn member_field<Ret, Fun>(
&self,
guild_id: impl Into<GuildId>,
user_id: impl Into<UserId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&Member) -> Ret,
pub fn member_field<Ret, Fun>(
&self,
guild_id: impl Into<GuildId>,
user_id: impl Into<UserId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&Member) -> Ret,
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);
}
pub fn guild_roles(
&self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<RoleId, Role>>
This method clones and returns all unavailable guilds.
sourcepub fn guild_channels(
&self,
guild_id: impl Into<GuildId>
) -> Option<DashMap<ChannelId, GuildChannel>>
pub fn guild_channels(
&self,
guild_id: impl Into<GuildId>
) -> Option<DashMap<ChannelId, GuildChannel>>
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 guild_categories(
&self,
guild_id: impl Into<GuildId>
) -> Option<DashMap<ChannelId, ChannelCategory>>
pub fn guild_categories(
&self,
guild_id: impl Into<GuildId>
) -> Option<DashMap<ChannelId, ChannelCategory>>
This method returns all categories from a guild of with the given guild_id
.
sourcepub fn shard_count(&self) -> u64
pub fn shard_count(&self) -> u64
Returns the number of shards.
sourcepub fn message<C, M>(&self, channel_id: C, message_id: M) -> Option<Message> where
C: Into<ChannelId>,
M: Into<MessageId>,
pub fn message<C, M>(&self, channel_id: C, message_id: M) -> Option<Message> 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."),
};
sourcepub fn private_channel(
&self,
channel_id: impl Into<ChannelId>
) -> Option<PrivateChannel>
pub fn private_channel(
&self,
channel_id: impl Into<ChannelId>
) -> Option<PrivateChannel>
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);
}
sourcepub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<Role> where
G: Into<GuildId>,
R: Into<RoleId>,
pub fn role<G, R>(&self, guild_id: G, role_id: R) -> Option<Role> 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);
}
sourcepub fn settings(&self) -> Settings
pub fn settings(&self) -> Settings
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<User>
pub fn user<U: Into<UserId>>(&self, user_id: U) -> Option<User>
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 category<C: Into<ChannelId>>(
&self,
channel_id: C
) -> Option<ChannelCategory>
pub fn category<C: Into<ChannelId>>(
&self,
channel_id: C
) -> Option<ChannelCategory>
Clones a category matching the channel_id
and returns it.
sourcepub fn categories(&self) -> DashMap<ChannelId, ChannelCategory>
pub fn categories(&self) -> DashMap<ChannelId, ChannelCategory>
Clones all categories and returns them.
sourcepub fn category_count(&self) -> usize
pub fn category_count(&self) -> usize
Returns the amount of cached categories.
sourcepub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId>
pub fn channel_category_id(&self, channel_id: ChannelId) -> Option<ChannelId>
Returns the optional category ID of a channel.
sourcepub fn current_user(&self) -> CurrentUser
pub fn current_user(&self) -> CurrentUser
This method clones and returns the user used by the bot.
sourcepub fn current_user_id(&self) -> UserId
pub fn current_user_id(&self) -> UserId
This method returns the bot’s ID.
sourcepub fn current_user_field<Ret: Clone, Fun>(&self, field_selector: Fun) -> Ret where
Fun: FnOnce(&CurrentUser) -> Ret,
pub fn current_user_field<Ret: Clone, Fun>(&self, field_selector: Fun) -> Ret where
Fun: FnOnce(&CurrentUser) -> Ret,
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);
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.
Trait Implementations
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
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
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
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more