Struct serenity::cache::Cache [] [src]

pub struct Cache {
    pub channels: HashMap<ChannelId, Arc<RwLock<GuildChannel>>>,
    pub groups: HashMap<ChannelId, Arc<RwLock<Group>>>,
    pub guilds: HashMap<GuildId, Arc<RwLock<Guild>>>,
    pub notes: HashMap<UserId, String>,
    pub presences: HashMap<UserId, Presence>,
    pub private_channels: HashMap<ChannelId, Arc<RwLock<PrivateChannel>>>,
    pub shard_count: u64,
    pub unavailable_guilds: HashSet<GuildId>,
    pub user: CurrentUser,
    pub users: HashMap<UserId, Arc<RwLock<User>>>,
}

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.

Use by the Context

The Context will automatically attempt to pull from the cache for you. For example, the Context::get_channel method will attempt to find the channel in the cache. If it can not find it, it will perform a request through the REST API, and then insert a clone of the channel - if found - into the Cache.

This allows you to only need to perform the Context::get_channel call, and not need to first search through the cache - and if not found - then perform an HTTP request through the Context or http module.

Additionally, note that some information received through events can not be retrieved through the REST API. This is information such as Roles in Guilds.

Fields

A map of channels in Guilds 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.

A map of the groups that the current user is in.

For bot users this will always be empty, except for in special cases.

A map of guilds with full data available. This includes data like Roles and Emojis that are not available through the REST API.

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.

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.

A map of direct message channels that the current user has open with other users.

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::GuildCreates.

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.

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]

Fetches the number of Members 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 serenity::client::CACHE;
use std::thread;
use std::time::Duration;

client.on_ready(|ctx, _| {
    // 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", CACHE.read().unwrap().unknown_members());
});

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:

use serenity::client::CACHE;

let amount = CACHE.read().unwrap().all_private_channels().len();

println!("There are {} private channels", amount);

Fetches a vector of all Guilds' Ids that are stored in the cache.

Note that if you are utilizing multiple Shards, 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:

use serenity::client::CACHE;

client.on_ready(|_, _| {
    println!("Guilds in the Cache: {:?}", CACHE.read().unwrap().all_guilds());
});

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:

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:

use serenity::client::CACHE;

let cache = CACHE.read()?;

if let Some(guild) = cache.guild(7) {
    println!("Guild name: {}", guild.read().unwrap().name);
}

Retrieves a reference to a Guild's channel. Unlike get_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:

use serenity::client::CACHE;

let cache = CACHE.read().unwrap();

let channel = match cache.get_guild_channel(message.channel_id) {
    Some(channel) => channel,
    None => {
        if let Err(why) = message.channel_id.say("Could not find guild's channel data") {
            println!("Error sending message: {:?}", why);
        }

        return;
    },
};

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:

use serenity::client::CACHE;

let cache = CACHE.read()?;

if let Some(group) = cache.group(7) {
    println!("Owner Id: {}", group.read().unwrap().owner_id);
}

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:

use serenity::CACHE;

let cache = CACHE.read().unwrap();
let member = {
    let channel = match cache.get_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.get_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);
}

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 send a message:

use serenity::client::CACHE;

let cache = CACHE.read()?;

if let Some(channel) = cache.private_channel(7) {
    channel.read().unwrap().say("Hello there!");
}

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:

use serenity::client::CACHE;

let cache = CACHE.read()?;

if let Some(role) = cache.role(7, 77) {
    println!("Role with Id 77 is called {}", role.name);
}

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:

use serenity::client::CACHE;

let cache = CACHE.read()?;

if let Some(user) = cache.user(7) {
    println!("User with Id 7 is currently named {}", user.read().unwrap().name);
}

Deprecated since 0.1.5

: Use channel instead.

Alias of channel.

Deprecated since 0.1.5

: Use guild instead.

Alias of guild.

Deprecated since 0.1.5

: Use guild_channel instead.

Alias of guild_channel.

Deprecated since 0.1.5

: Use member instead.

Alias of member.

Deprecated since 0.1.5

: Use private_channel instead.

Alias of private_channel.

Deprecated since 0.1.5

: Use role instead.

Alias of role.

Deprecated since 0.1.5

: Use user instead.

Alias of user.

Trait Implementations

impl Clone for Cache
[src]

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

impl Debug for Cache
[src]

Formats the value using the given formatter.

impl Default for Cache
[src]

Returns the "default value" for a type. Read more