[−][src]Struct serenity::cache::Cache
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.
The cache will clone all values when calling its methods.
Implementations
impl Cache
[src]
pub fn new() -> Self
[src]
Creates a new cache.
pub fn new_with_settings(settings: Settings) -> Self
[src]
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);
pub async fn unknown_members<'_>(&'_ self) -> u64
[src]
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_guilds
, 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::delay_for(Duration::from_secs(5)).await; println!("{} unknown members", ctx.cache.unknown_members().await); } } let mut client =Client::new("token").event_handler(Handler).await?; client.start().await?;
pub async fn private_channels<'_>(
&'_ self
) -> HashMap<ChannelId, PrivateChannel>
[src]
&'_ self
) -> HashMap<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().await.len(); println!("There are {} private channels", amount);
pub async fn guilds<'_>(&'_ self) -> Vec<GuildId>
[src]
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); } }
pub async fn channel<C: Into<ChannelId>, '_>(&'_ self, id: C) -> Option<Channel>
[src]
Retrieves a Channel
from the cache based on the given Id.
This will search the channels
map, then the 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 guild<G: Into<GuildId>, '_>(&'_ self, id: G) -> Option<Guild>
[src]
Clones an entire guild from the cache based on the given id
.
In order to clone only a field of the guild, use [`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); }
pub async fn guild_field<Ret, Fun, '_>(
&'_ self,
id: impl Into<GuildId>,
field_selector: Fun
) -> Option<Ret> where
Fun: FnOnce(&Guild) -> Ret,
[src]
&'_ 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()).await { println!("Guild channels count: {}", channel_len); }
pub async fn guild_count<'_>(&'_ self) -> usize
[src]
Returns the number of cached guilds.
pub async fn guild_channel<C: Into<ChannelId>, '_>(
&'_ self,
id: C
) -> Option<GuildChannel>
[src]
&'_ self,
id: C
) -> Option<GuildChannel>
Retrieves a reference to a Guild
's channel. Unlike 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
Client::on_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::new("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,
[src]
&'_ 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); }
pub async fn member<G, U, '_>(
&'_ self,
guild_id: G,
user_id: U
) -> Option<Member> where
G: Into<GuildId>,
U: Into<UserId>,
[src]
&'_ 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
Client::on_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); }
pub async 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,
[src]
&'_ 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()).await { println!("Member's nick: {}", nick); }
pub async fn guild_roles<'_>(
&'_ self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<RoleId, Role>>
[src]
&'_ self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<RoleId, Role>>
pub async fn unavailable_guilds<'_>(&'_ self) -> HashSet<GuildId>
[src]
This method clones and returns all unavailable guilds.
pub async fn guild_channels<'_>(
&'_ self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<ChannelId, GuildChannel>>
[src]
&'_ self,
guild_id: impl Into<GuildId>
) -> Option<HashMap<ChannelId, GuildChannel>>
This method returns all channels from a guild of with the given guild_id
.
pub async fn guild_channel_count<'_>(&'_ self) -> usize
[src]
Returns the number of guild channels in the cache.
pub async fn shard_count<'_>(&'_ self) -> u64
[src]
Returns the number of shards.
pub async fn message<C, M, '_>(
&'_ self,
channel_id: C,
message_id: M
) -> Option<Message> where
C: Into<ChannelId>,
M: Into<MessageId>,
[src]
&'_ 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).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>
[src]
&'_ self,
channel_id: impl Into<ChannelId>
) -> Option<PrivateChannel>
Retrieves a PrivateChannel
from the cache's 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); }
pub async fn role<G, R, '_>(&'_ self, guild_id: G, role_id: R) -> Option<Role> where
G: Into<GuildId>,
R: Into<RoleId>,
[src]
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).await { println!("Role with Id 77 is called {}", role.name); }
pub async fn settings<'_>(&'_ self) -> Settings
[src]
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);
pub async fn set_max_messages<'_>(&'_ self, max: usize)
[src]
Sets the maximum amount of messages per channel to cache.
By default, no messages will be cached.
pub async fn user<U: Into<UserId>, '_>(&'_ self, user_id: U) -> Option<User>
[src]
Retrieves a User
from the cache's 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); }
pub async fn users<'_>(&'_ self) -> HashMap<UserId, User>
[src]
Clones all users and returns them.
pub async fn user_count<'_>(&'_ self) -> usize
[src]
Returns the amount of cached users.
pub async fn category<C: Into<ChannelId>, '_>(
&'_ self,
channel_id: C
) -> Option<ChannelCategory>
[src]
&'_ self,
channel_id: C
) -> Option<ChannelCategory>
Clones a category matching the channel_id
and returns it.
pub async fn categories<'_>(&'_ self) -> HashMap<ChannelId, ChannelCategory>
[src]
Clones all categories and returns them.
pub async fn category_count<'_>(&'_ self) -> usize
[src]
Returns the amount of cached categories.
pub async fn current_user<'_>(&'_ self) -> CurrentUser
[src]
This method clones and returns the user used by the bot.
pub async fn current_user_id<'_>(&'_ self) -> UserId
[src]
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,
[src]
&'_ 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);
pub async fn update<E: CacheUpdate, '_, '_>(
&'_ self,
e: &'_ mut E
) -> Option<E::Output>
[src]
&'_ 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
impl AsRef<Cache> for Context
[src]
impl AsRef<Cache> for Arc<Context>
[src]
impl AsRef<Cache> for Cache
[src]
impl<'_, '_> AsRef<Cache> for (&'_ Arc<Cache>, &'_ Http)
[src]
impl Debug for Cache
[src]
impl Default for Cache
[src]
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
impl<T> Any for T where
T: 'static + ?Sized,
[src]
T: 'static + ?Sized,
impl<T> Borrow<T> for T where
T: ?Sized,
[src]
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
[src]
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
[src]
impl<T> From<T> for T
[src]
impl<T> Instrument for T
[src]
fn instrument(self, span: Span) -> Instrumented<Self>
[src]
fn in_current_span(self) -> Instrumented<Self>
[src]
impl<T, U> Into<U> for T where
U: From<T>,
[src]
U: From<T>,
impl<T> Same<T> for T
type Output = T
Should always be Self
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = Infallible
The type returned in the event of a conversion error.
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
[src]
impl<T, U> TryInto<U> for T where
U: TryFrom<T>,
[src]
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error
The type returned in the event of a conversion error.
fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>
[src]
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
V: MultiLane<T>,
fn vzip(self) -> V
impl<T> WithSubscriber for T
[src]
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
[src]
S: Into<Dispatch>,