Struct serenity::cache::Cache [−][src]
#[non_exhaustive]pub struct Cache { /* fields omitted */ }
Expand description
Implementations
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 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().await); } } let mut client = Client::builder("token").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().await.len(); println!("There are {} private channels", amount);
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().await.len(); println!("Guilds in the Cache: {}", guilds); } }
Retrieves a Channel
from the cache based on the given Id.
This will search the Self::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 maps or methods:
pub async fn channel_messages_field<T>(
&self,
channel_id: impl Into<ChannelId>,
selector: impl FnOnce(MessageIterator<'_>) -> T
) -> Option<T>
pub async fn channel_messages_field<T>(
&self,
channel_id: impl Into<ChannelId>,
selector: impl FnOnce(MessageIterator<'_>) -> 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(|m| m.author.id == 8).cloned().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).await { 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()).await { 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).await { 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").event_handler(Handler).await?; client.start().await?;
pub async fn guild_channel_field<Ret, Fun>(
&self,
id: impl Into<ChannelId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&GuildChannel) -> Ret,
pub async 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()).await { 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).await { 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).await { 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()).await { println!("Member's nick: {}", nick); }
This method clones and returns all unavailable guilds.
pub async fn guild_channels(
&self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<ChannelId, GuildChannel>>
pub async fn guild_channels(
&self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<ChannelId, GuildChannel>>
This method returns all channels from a guild of with the given guild_id
.
Returns the number of guild channels in the cache.
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).await { Some(m) => assert_eq!(message.content, m.content), None => println!("No message found in cache."), };
pub async fn private_channel(
&self,
channel_id: impl Into<ChannelId>
) -> Option<PrivateChannel>
pub async 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).await { 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).await { 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().await.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).await { println!("User with Id 7 is currently named {}", user.name); }
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.
pub async fn current_user_field<Ret: Clone, Fun>(
&self,
field_selector: Fun
) -> Ret where
Fun: FnOnce(&CurrentUser) -> Ret,
pub async 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).await; 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.