[−][src]Struct serenity::cache::Cache
A cache of all events received over a Shard
, where storing at least
some data from the event is possible.
This acts as a cache, to avoid making requests over the REST API through the
http
module where possible. All fields are public, and do not have
getters, to allow you more flexibility with the stored data. However, this
allows data to be "corrupted", and may or may not cause misfunctions
within the library. Mutate data at your own discretion.
Fields
channels: HashMap<ChannelId, Arc<RwLock<GuildChannel>>>
A map of channels in Guild
s that the current user has received data
for.
When a Event::GuildDelete
or Event::GuildUnavailable
is
received and processed by the cache, the relevant channels are also
removed from this map.
categories: HashMap<ChannelId, Arc<RwLock<ChannelCategory>>>
A map of channel categories.
groups: HashMap<ChannelId, Arc<RwLock<Group>>>
A map of the groups that the current user is in.
For bot users this will always be empty, except for in special cases.
guilds: HashMap<GuildId, Arc<RwLock<Guild>>>
A map of guilds with full data available. This includes data like
Role
s and Emoji
s that are not available through the REST API.
messages: HashMap<ChannelId, HashMap<MessageId, Message>>
A map of channels to messages.
This is a map of channel IDs to another map of message IDs to messages.
This keeps only the ten most recent messages.
notes: HashMap<UserId, String>
A map of notes that a user has made for individual users.
An empty note is equivalent to having no note, and creating an empty note is equivalent to deleting a note.
This will always be empty for bot users.
presences: HashMap<UserId, Presence>
A map of users' presences. This is updated in real-time. Note that status updates are often "eaten" by the gateway, and this should not be treated as being entirely 100% accurate.
private_channels: HashMap<ChannelId, Arc<RwLock<PrivateChannel>>>
A map of direct message channels that the current user has open with other users.
shard_count: u64
The total number of shards being used by the bot.
A list of guilds which are "unavailable". Refer to the documentation for
Event::GuildUnavailable
for more information on when this can occur.
Additionally, guilds are always unavailable for bot users when a Ready
is received. Guilds are "sent in" over time through the receiving of
Event::GuildCreate
s.
user: CurrentUser
The current user "logged in" and for which events are being received for.
The current user contains information that a regular User
does not,
such as whether it is a bot, whether the user is verified, etc.
Refer to the documentation for CurrentUser
for more information.
users: HashMap<UserId, Arc<RwLock<User>>>
A map of users that the current user sees.
Users are added to - and updated from - this map via the following received events:
Note, however, that users are not removed from the map on removal
events such as GuildMemberRemove
, as other
structs such as members or recipients may still exist.
Methods
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 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; impl EventHandler for Handler { 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. thread::sleep(Duration::from_secs(5)); println!("{} unknown members", ctx.cache.read().unknown_members()); } } let mut client = Client::new("token", Handler).unwrap(); client.start().unwrap();
pub fn all_private_channels(&self) -> Vec<&ChannelId>
[src]
Fetches a vector of all PrivateChannel
and Group
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.read().all_private_channels().len(); println!("There are {} private channels", amount);
pub fn all_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; impl EventHandler for Handler { fn ready(&self, context: Context, _: Ready) { let guilds = context.cache.read().guilds.len(); println!("Guilds in the Cache: {}", guilds); } }
pub 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, the private_channels
map, and
then the map of groups
to find the channel.
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 fn guild<G: Into<GuildId>>(&self, id: G) -> Option<Arc<RwLock<Guild>>>
[src]
Retrieves a guild from the cache based on the given Id.
The only advantage of this method is that you can pass in anything that
is indirectly a GuildId
.
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.read().guild(7) { println!("Guild name: {}", guild.read().name); }
pub fn guild_channel<C: Into<ChannelId>>(
&self,
id: C
) -> Option<Arc<RwLock<GuildChannel>>>
[src]
&self,
id: C
) -> Option<Arc<RwLock<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; impl EventHandler for Handler { fn message(&self, context: Context, message: Message) { let cache = context.cache.read(); let channel = match cache.guild_channel(message.channel_id) { Some(channel) => channel, None => { if let Err(why) = message.channel_id.say(&context.http, "Could not find guild's channel data") { println!("Error sending message: {:?}", why); } return; }, }; } } let mut client = Client::new("token", Handler).unwrap(); client.start().unwrap();
pub fn group<C: Into<ChannelId>>(&self, id: C) -> Option<Arc<RwLock<Group>>>
[src]
Retrieves a reference to a Group
from the cache based on the given
associated channel Id.
The only advantage of this method is that you can pass in anything that
is indirectly a ChannelId
.
Examples
Retrieve a group from the cache and print its owner's id:
if let Some(group) = cache.read().group(7) { println!("Owner Id: {}", group.read().owner_id); }
pub fn member<G, U>(&self, guild_id: G, user_id: U) -> Option<Member> where
G: Into<GuildId>,
U: Into<UserId>,
[src]
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 cache = cache.read(); let member = { let channel = match cache.guild_channel(message.channel_id) { Some(channel) => channel, None => { if let Err(why) = message.channel_id.say("Error finding channel data") { println!("Error sending message: {:?}", why); } }, }; match cache.member(channel.guild_id, message.author.id) { Some(member) => member, None => { if let Err(why) = message.channel_id.say("Error finding member data") { println!("Error sending message: {:?}", why); } }, } }; let msg = format!("You have {} roles", member.roles.len()); if let Err(why) = message.channel_id.say(&msg) { println!("Error sending message: {:?}", why); }
pub fn message<C, M>(&self, channel_id: C, message_id: M) -> Option<Message> where
C: Into<ChannelId>,
M: Into<MessageId>,
[src]
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:
let cache = cache.read(); let fetched_message = cache.message(message.channel_id, message.id); match fetched_message { Some(m) => { assert_eq!(message.content, m.content); }, None => { println!("No message found in cache."); }, }
pub fn private_channel<C: Into<ChannelId>>(
&self,
channel_id: C
) -> Option<Arc<RwLock<PrivateChannel>>>
[src]
&self,
channel_id: C
) -> Option<Arc<RwLock<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) { let channel_reader = channel.read(); let user_reader = channel_reader.recipient.read(); println!("The recipient is {}", user_reader.name); }
pub 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.read().role(7, 77) { println!("Role with Id 77 is called {}", role.name); }
pub fn settings(&self) -> &Settings
[src]
Returns an immutable reference to 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);
pub fn settings_mut(&mut self) -> &mut Settings
[src]
Returns a mutable reference to the settings.
Examples
Create a new cache and modify the settings afterwards:
use serenity::cache::Cache; let mut cache = Cache::new(); cache.settings_mut().max_messages(10);
pub fn user<U: Into<UserId>>(&self, user_id: U) -> Option<Arc<RwLock<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.read().user(7) { println!("User with Id 7 is currently named {}", user.read().name); }
pub fn categories<C: Into<ChannelId>>(
&self,
channel_id: C
) -> Option<Arc<RwLock<ChannelCategory>>>
[src]
&self,
channel_id: C
) -> Option<Arc<RwLock<ChannelCategory>>>
pub fn update<E: CacheUpdate>(&mut self, e: &mut E) -> Option<E::Output>
[src]
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
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> CloneAny for T where
T: Clone + Any,
[src]
T: Clone + Any,
fn clone_any(&self) -> Box<dyn CloneAny + 'static>
[src]
fn clone_any_send(&self) -> Box<dyn CloneAny + 'static + Send> where
T: Send,
[src]
T: Send,
fn clone_any_sync(&self) -> Box<dyn CloneAny + 'static + Sync> where
T: Sync,
[src]
T: Sync,
fn clone_any_send_sync(&self) -> Box<dyn CloneAny + 'static + Sync + Send> where
T: Send + Sync,
[src]
T: Send + Sync,
impl<T> DebugAny for T where
T: Any + Debug,
[src]
T: Any + Debug,
impl<T> From<T> for T
[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> ToOwned for T where
T: Clone,
[src]
T: Clone,
type Owned = T
The resulting type after obtaining ownership.
fn to_owned(&self) -> T
[src]
fn clone_into(&self, target: &mut T)
[src]
impl<T, U> TryFrom<U> for T where
U: Into<T>,
[src]
U: Into<T>,
type Error = !
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<T, U> TryInto<U> for T where
U: TryFrom<T>,
U: TryFrom<T>,
impl<T> UnsafeAny for T where
T: Any,
T: Any,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
V: MultiLane<T>,