aboutsummaryrefslogtreecommitdiff
path: root/src/model/guild
diff options
context:
space:
mode:
authorLakelezz <[email protected]>2018-12-18 20:55:32 +0100
committerAlex M. M <[email protected]>2018-12-18 20:55:32 +0100
commit8cb1bdc6cf992cc55810f5af753666d54f2237d5 (patch)
tree052e2f425a6117e45323886bb2b2b683b6d5a1e8 /src/model/guild
parentMutably borrow on `ChannelId`'s `edit`-method. (#447) (diff)
downloadserenity-8cb1bdc6cf992cc55810f5af753666d54f2237d5.tar.xz
serenity-8cb1bdc6cf992cc55810f5af753666d54f2237d5.zip
Remove global Cache (#448)
* Update to use Rust 2018. * Update examples and use Rust 2018. * Pass cache via `Context` around instead of being global. * Remove `lazy_static` from `cache`-feature. * Update examples to use `Context`'s cache. * Replace cache's update-timeout-setting with `update_cache_timeout`. * Update documentation to stop using global cache. * Move `HttpAndCache` to `lib.rs`. * Add `__nonexhaustive`-field to `CacheAndHttp`. * Add `__nonexhaustive` in `CacheAndHttp`-initialisers. * Avoid `__nonexhaustive`-usage in doctest. * Remove unnecessary comma in `cfg`-attribute.
Diffstat (limited to 'src/model/guild')
-rw-r--r--src/model/guild/emoji.rs55
-rw-r--r--src/model/guild/guild_id.rs20
-rw-r--r--src/model/guild/member.rs36
-rw-r--r--src/model/guild/mod.rs91
-rw-r--r--src/model/guild/partial_guild.rs12
-rw-r--r--src/model/guild/role.rs32
6 files changed, 139 insertions, 107 deletions
diff --git a/src/model/guild/emoji.rs b/src/model/guild/emoji.rs
index 03c7a7e..dde379e 100644
--- a/src/model/guild/emoji.rs
+++ b/src/model/guild/emoji.rs
@@ -15,7 +15,11 @@ use super::super::ModelError;
#[cfg(all(feature = "cache", feature = "model"))]
use super::super::id::GuildId;
#[cfg(all(feature = "cache", feature = "model"))]
-use crate::{CACHE, http};
+use crate::{cache::Cache, http};
+#[cfg(all(feature = "cache", feature = "model"))]
+use parking_lot::RwLock;
+#[cfg(all(feature = "cache", feature = "model"))]
+use std::sync::Arc;
/// Represents a custom guild emoji, which can either be created using the API,
/// or via an integration. Emojis created using the API only work within the
@@ -52,7 +56,7 @@ impl Emoji {
///
/// **Note**: Only user accounts may use this method.
///
- /// [Manage Emojis]:
+ /// [Manage Emojis]:
/// ../permissions/struct.Permissions.html#associatedconstant.MANAGE_EMOJIS
///
/// # Examples
@@ -60,8 +64,14 @@ impl Emoji {
/// Delete a given emoji:
///
/// ```rust,no_run
- /// # use serenity::model::guild::Emoji;
- /// # use serenity::model::id::EmojiId;
+ /// # extern crate parking_lot;
+ /// # extern crate serenity;
+ /// #
+ /// # use serenity::{cache::Cache, model::{guild::Emoji, id::EmojiId}};
+ /// # use parking_lot::RwLock;
+ /// # use std::sync::Arc;
+ /// #
+ /// # let cache = Arc::new(RwLock::new(Cache::default()));
/// #
/// # let mut emoji = Emoji {
/// # animated: false,
@@ -73,14 +83,14 @@ impl Emoji {
/// # };
/// #
/// // assuming emoji has been set already
- /// match emoji.delete() {
+ /// match emoji.delete(&cache) {
/// Ok(()) => println!("Emoji deleted."),
/// Err(_) => println!("Could not delete emoji.")
/// }
/// ```
#[cfg(feature = "cache")]
- pub fn delete(&self) -> Result<()> {
- match self.find_guild_id() {
+ pub fn delete(&self, cache: &Arc<RwLock<Cache>>) -> Result<()> {
+ match self.find_guild_id(&cache) {
Some(guild_id) => http::delete_emoji(guild_id.0, self.id.0),
None => Err(Error::Model(ModelError::ItemMissing)),
}
@@ -99,9 +109,9 @@ impl Emoji {
/// Change the name of an emoji:
///
/// ```rust,no_run
- /// # use serenity::model::guild::Emoji;
- /// # use serenity::model::id::EmojiId;
+ /// # use serenity::{command, model::{guild::Emoji, id::EmojiId}};
/// #
+ /// # command!(example(context) {
/// # let mut emoji = Emoji {
/// # animated: false,
/// # id: EmojiId(7),
@@ -110,14 +120,14 @@ impl Emoji {
/// # require_colons: false,
/// # roles: vec![],
/// # };
- /// #
/// // assuming emoji has been set already
- /// let _ = emoji.edit("blobuwu");
+ /// let _ = emoji.edit(&context.cache, "blobuwu");
/// assert_eq!(emoji.name, "blobuwu");
+ /// # });
/// ```
#[cfg(feature = "cache")]
- pub fn edit(&mut self, name: &str) -> Result<()> {
- match self.find_guild_id() {
+ pub fn edit(&mut self, cache: &Arc<RwLock<Cache>>, name: &str) -> Result<()> {
+ match self.find_guild_id(&cache) {
Some(guild_id) => {
let map = json!({
"name": name,
@@ -145,8 +155,14 @@ impl Emoji {
/// Print the guild id that owns this emoji:
///
/// ```rust,no_run
- /// # use serenity::model::guild::Emoji;
- /// # use serenity::model::id::EmojiId;
+ /// # extern crate parking_lot;
+ /// # extern crate serenity;
+ /// #
+ /// # use serenity::{cache::Cache, model::{guild::Emoji, id::EmojiId}};
+ /// # use parking_lot::RwLock;
+ /// # use std::sync::Arc;
+ /// #
+ /// # let cache = Arc::new(RwLock::new(Cache::default()));
/// #
/// # let mut emoji = Emoji {
/// # animated: false,
@@ -158,13 +174,13 @@ impl Emoji {
/// # };
/// #
/// // assuming emoji has been set already
- /// if let Some(guild_id) = emoji.find_guild_id() {
+ /// if let Some(guild_id) = emoji.find_guild_id(&cache) {
/// println!("{} is owned by {}", emoji.name, guild_id);
/// }
/// ```
#[cfg(feature = "cache")]
- pub fn find_guild_id(&self) -> Option<GuildId> {
- for guild in CACHE.read().guilds.values() {
+ pub fn find_guild_id(&self, cache: &Arc<RwLock<Cache>>) -> Option<GuildId> {
+ for guild in cache.read().guilds.values() {
let guild = guild.read();
if guild.emojis.contains_key(&self.id) {
@@ -182,8 +198,7 @@ impl Emoji {
/// Print the direct link to the given emoji:
///
/// ```rust,no_run
- /// # use serenity::model::guild::Emoji;
- /// # use serenity::model::id::EmojiId;
+ /// # use serenity::model::{guild::Emoji, id::EmojiId};
/// #
/// # let mut emoji = Emoji {
/// # animated: false,
diff --git a/src/model/guild/guild_id.rs b/src/model/guild/guild_id.rs
index c488b52..3146c78 100644
--- a/src/model/guild/guild_id.rs
+++ b/src/model/guild/guild_id.rs
@@ -1,7 +1,9 @@
-use crate::model::prelude::*;
+use crate::{model::prelude::*};
+#[cfg(feature = "client")]
+use crate::client::Context;
#[cfg(all(feature = "cache", feature = "model"))]
-use crate::CACHE;
+use crate::cache::Cache;
#[cfg(feature = "model")]
use crate::builder::{EditGuild, EditMember, EditRole};
#[cfg(feature = "model")]
@@ -407,7 +409,7 @@ impl GuildId {
/// [`Guild`]: ../guild/struct.Guild.html
#[cfg(feature = "cache")]
#[inline]
- pub fn to_guild_cached(self) -> Option<Arc<RwLock<Guild>>> { CACHE.read().guild(self) }
+ pub fn to_guild_cached(self, cache: &Arc<RwLock<Cache>>) -> Option<Arc<RwLock<Guild>>> { cache.read().guild(self) }
/// Requests [`PartialGuild`] over REST API.
///
@@ -456,14 +458,14 @@ impl GuildId {
/// [`Guild`]: ../guild/struct.Guild.html
/// [`Member`]: ../guild/struct.Member.html
#[inline]
- pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> {
- self._member(user_id.into())
+ pub fn member<U: Into<UserId>>(&self, context: &Context, user_id: U) -> Result<Member> {
+ self._member(&context, user_id.into())
}
- fn _member(&self, user_id: UserId) -> Result<Member> {
+ fn _member(&self, context: &Context, user_id: UserId) -> Result<Member> {
#[cfg(feature = "cache")]
{
- if let Some(member) = CACHE.read().member(self.0, user_id) {
+ if let Some(member) = context.cache.read().member(self.0, user_id) {
return Ok(member);
}
}
@@ -563,7 +565,9 @@ impl GuildId {
/// [`utils::shard_id`]: ../../utils/fn.shard_id.html
#[cfg(all(feature = "cache", feature = "utils"))]
#[inline]
- pub fn shard_id(&self) -> u64 { crate::utils::shard_id(self.0, CACHE.read().shard_count) }
+ pub fn shard_id(&self, cache: &Arc<RwLock<Cache>>) -> u64 {
+ crate::utils::shard_id(self.0, cache.read().shard_count)
+ }
/// Returns the Id of the shard associated with the guild.
///
diff --git a/src/model/guild/member.rs b/src/model/guild/member.rs
index cbda4c3..d969bd0 100644
--- a/src/model/guild/member.rs
+++ b/src/model/guild/member.rs
@@ -1,4 +1,4 @@
-use crate::model::prelude::*;
+use crate::{model::prelude::*};
use chrono::{DateTime, FixedOffset};
use std::fmt::{
Display,
@@ -7,6 +7,8 @@ use std::fmt::{
};
use super::deserialize_sync_user;
+#[cfg(feature = "client")]
+use crate::client::Context;
#[cfg(all(feature = "builder", feature = "cache", feature = "model"))]
use crate::builder::EditMember;
#[cfg(all(feature = "cache", feature = "model"))]
@@ -16,7 +18,7 @@ use std::borrow::Cow;
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
use crate::utils::Colour;
#[cfg(all(feature = "cache", feature = "model"))]
-use crate::{CACHE, http, utils};
+use crate::{cache::Cache, http, utils};
/// A trait for allowing both u8 or &str or (u8, &str) to be passed into the `ban` methods in `Guild` and `Member`.
pub trait BanOptions {
@@ -169,8 +171,8 @@ impl Member {
/// Determines the member's colour.
#[cfg(all(feature = "cache", feature = "utils"))]
- pub fn colour(&self) -> Option<Colour> {
- let cache = CACHE.read();
+ pub fn colour(&self, cache: &Arc<RwLock<Cache>>) -> Option<Colour> {
+ let cache = cache.read();
let guild = cache.guilds.get(&self.guild_id)?.read();
let mut roles = self.roles
@@ -191,8 +193,8 @@ impl Member {
/// (This returns the first channel that can be read by the member, if there isn't
/// one returns `None`)
#[cfg(feature = "cache")]
- pub fn default_channel(&self) -> Option<Arc<RwLock<GuildChannel>>> {
- let guild = match self.guild_id.to_guild_cached() {
+ pub fn default_channel(&self, cache: &Arc<RwLock<Cache>>) -> Option<Arc<RwLock<GuildChannel>>> {
+ let guild = match self.guild_id.to_guild_cached(&cache) {
Some(guild) => guild,
None => return None,
};
@@ -257,8 +259,8 @@ impl Member {
/// position. If two or more roles have the same highest position, then the
/// role with the lowest ID is the highest.
#[cfg(feature = "cache")]
- pub fn highest_role_info(&self) -> Option<(RoleId, i64)> {
- let guild = self.guild_id.to_guild_cached()?;
+ pub fn highest_role_info(&self, cache: &Arc<RwLock<Cache>>) -> Option<(RoleId, i64)> {
+ let guild = self.guild_id.to_guild_cached(&cache)?;
let reader = guild.try_read()?;
let mut highest = None;
@@ -315,20 +317,20 @@ impl Member {
/// [`ModelError::GuildNotFound`]: ../error/enum.Error.html#variant.GuildNotFound
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Kick Members]: ../permissions/struct.Permissions.html#associatedconstant.KICK_MEMBERS
- pub fn kick(&self) -> Result<()> {
+ pub fn kick(&self, context: &Context) -> Result<()> {
#[cfg(feature = "cache")]
{
- let cache = CACHE.read();
+ let locked_cache = context.cache.read();
- if let Some(guild) = cache.guilds.get(&self.guild_id) {
+ if let Some(guild) = locked_cache.guilds.get(&self.guild_id) {
let req = Permissions::KICK_MEMBERS;
let reader = guild.read();
- if !reader.has_perms(req) {
+ if !reader.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
- reader.check_hierarchy(self.user.read().id)?;
+ reader.check_hierarchy(&context.cache, self.user.read().id)?;
}
}
@@ -356,8 +358,8 @@ impl Member {
/// [`ModelError::GuildNotFound`]: ../error/enum.Error.html#variant.GuildNotFound
/// [`ModelError::ItemMissing`]: ../error/enum.Error.html#variant.ItemMissing
#[cfg(feature = "cache")]
- pub fn permissions(&self) -> Result<Permissions> {
- let guild = match self.guild_id.to_guild_cached() {
+ pub fn permissions(&self, cache: &Arc<RwLock<Cache>>) -> Result<Permissions> {
+ let guild = match self.guild_id.to_guild_cached(&cache) {
Some(guild) => guild,
None => return Err(From::from(ModelError::GuildNotFound)),
};
@@ -426,10 +428,10 @@ impl Member {
///
/// If role data can not be found for the member, then `None` is returned.
#[cfg(feature = "cache")]
- pub fn roles(&self) -> Option<Vec<Role>> {
+ pub fn roles(&self, cache: &Arc<RwLock<Cache>>) -> Option<Vec<Role>> {
self
.guild_id
- .to_guild_cached()
+ .to_guild_cached(&cache)
.map(|g| g
.read()
.roles
diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs
index 86cba3d..3ea8d06 100644
--- a/src/model/guild/mod.rs
+++ b/src/model/guild/mod.rs
@@ -17,13 +17,19 @@ pub use self::role::*;
pub use self::audit_log::*;
use chrono::{DateTime, FixedOffset};
-use crate::model::prelude::*;
+use crate::{model::prelude::*};
use serde::de::Error as DeError;
use serde_json;
use super::utils::*;
+#[cfg(feature = "client")]
+use crate::client::Context;
#[cfg(all(feature = "cache", feature = "model"))]
-use crate::CACHE;
+use crate::cache::Cache;
+#[cfg(all(feature = "cache", feature = "model"))]
+use parking_lot::RwLock;
+#[cfg(all(feature = "cache", feature = "model"))]
+use std::sync::Arc;
#[cfg(feature = "model")]
use crate::http;
#[cfg(feature = "model")]
@@ -146,10 +152,10 @@ pub struct Guild {
#[cfg(feature = "model")]
impl Guild {
#[cfg(feature = "cache")]
- fn check_hierarchy(&self, other_user: UserId) -> Result<()> {
- let current_id = CACHE.read().user.id;
+ fn check_hierarchy(&self, cache: &Arc<RwLock<Cache>>, other_user: UserId) -> Result<()> {
+ let current_id = cache.read().user.id;
- if let Some(higher) = self.greater_member_hierarchy(other_user, current_id) {
+ if let Some(higher) = self.greater_member_hierarchy(&cache, other_user, current_id) {
if higher != current_id {
return Err(Error::Model(ModelError::Hierarchy));
}
@@ -189,8 +195,8 @@ impl Guild {
}
#[cfg(feature = "cache")]
- fn has_perms(&self, mut permissions: Permissions) -> bool {
- let user_id = CACHE.read().user.id;
+ fn has_perms(&self, cache: &Arc<RwLock<Cache>>, mut permissions: Permissions) -> bool {
+ let user_id = cache.read().user.id;
let perms = self.member_permissions(user_id);
permissions.remove(perms);
@@ -228,20 +234,20 @@ impl Guild {
/// [`User`]: ../user/struct.User.html
/// [Ban Members]: ../permissions/struct.Permissions.html#associatedconstant.BAN_MEMBERS
#[inline]
- pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, user: U, options: &BO) -> Result<()> {
- self._ban(user.into(), options)
+ pub fn ban<U: Into<UserId>, BO: BanOptions>(&self, context: &Context, user: U, options: &BO) -> Result<()> {
+ self._ban(&context, user.into(), options)
}
- fn _ban<BO: BanOptions>(&self, user: UserId, options: &BO) -> Result<()> {
+ fn _ban<BO: BanOptions>(&self, context: &Context, user: UserId, options: &BO) -> Result<()> {
#[cfg(feature = "cache")]
{
let req = Permissions::BAN_MEMBERS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
- self.check_hierarchy(user)?;
+ self.check_hierarchy(&context.cache, user)?;
}
self.id.ban(user, options)
@@ -259,12 +265,12 @@ impl Guild {
/// [`Ban`]: struct.Ban.html
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Ban Members]: ../permissions/struct.Permissions.html#associatedconstant.BAN_MEMBERS
- pub fn bans(&self) -> Result<Vec<Ban>> {
+ pub fn bans(&self, context: &Context) -> Result<Vec<Ban>> {
#[cfg(feature = "cache")]
{
let req = Permissions::BAN_MEMBERS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -346,13 +352,13 @@ impl Guild {
/// [`Channel`]: ../channel/enum.Channel.html
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Manage Channels]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_CHANNELS
- pub fn create_channel<C>(&self, name: &str, kind: ChannelType, category: C) -> Result<GuildChannel>
+ pub fn create_channel<C>(&self, context: &Context, name: &str, kind: ChannelType, category: C) -> Result<GuildChannel>
where C: Into<Option<ChannelId>> {
#[cfg(feature = "cache")]
{
let req = Permissions::MANAGE_CHANNELS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -417,13 +423,13 @@ impl Guild {
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [`Role`]: struct.Role.html
/// [Manage Roles]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_ROLES
- pub fn create_role<F>(&self, f: F) -> Result<Role>
+ pub fn create_role<F>(&self, context: &Context, f: F) -> Result<Role>
where F: FnOnce(&mut EditRole) -> &mut EditRole {
#[cfg(feature = "cache")]
{
let req = Permissions::MANAGE_ROLES;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -442,10 +448,10 @@ impl Guild {
/// if the current user is not the guild owner.
///
/// [`ModelError::InvalidUser`]: ../error/enum.Error.html#variant.InvalidUser
- pub fn delete(&self) -> Result<PartialGuild> {
+ pub fn delete(&self, context: &Context) -> Result<PartialGuild> {
#[cfg(feature = "cache")]
{
- if self.owner_id != CACHE.read().user.id {
+ if self.owner_id != context.cache.read().user.id {
let req = Permissions::MANAGE_GUILD;
return Err(Error::Model(ModelError::InvalidPermissions(req)));
@@ -519,13 +525,13 @@ impl Guild {
///
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Manage Guild]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_GUILD
- pub fn edit<F>(&mut self, f: F) -> Result<()>
+ pub fn edit<F>(&mut self, context: &Context, f: F) -> Result<()>
where F: FnOnce(&mut EditGuild) -> &mut EditGuild {
#[cfg(feature = "cache")]
{
let req = Permissions::MANAGE_GUILD;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -600,12 +606,12 @@ impl Guild {
///
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Change Nickname]: ../permissions/struct.Permissions.html#associatedconstant.CHANGE_NICKNAME
- pub fn edit_nickname(&self, new_nickname: Option<&str>) -> Result<()> {
+ pub fn edit_nickname(&self, context: &Context, new_nickname: Option<&str>) -> Result<()> {
#[cfg(feature = "cache")]
{
let req = Permissions::CHANGE_NICKNAME;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -673,14 +679,15 @@ impl Guild {
/// [`position`]: struct.Role.html#structfield.position
#[cfg(feature = "cache")]
#[inline]
- pub fn greater_member_hierarchy<T, U>(&self, lhs_id: T, rhs_id: U)
+ pub fn greater_member_hierarchy<T, U>(&self, cache: &Arc<RwLock<Cache>>, lhs_id: T, rhs_id: U)
-> Option<UserId> where T: Into<UserId>, U: Into<UserId> {
- self._greater_member_hierarchy(lhs_id.into(), rhs_id.into())
+ self._greater_member_hierarchy(&cache, lhs_id.into(), rhs_id.into())
}
#[cfg(feature = "cache")]
fn _greater_member_hierarchy(
&self,
+ cache: &Arc<RwLock<Cache>>,
lhs_id: UserId,
rhs_id: UserId,
) -> Option<UserId> {
@@ -697,10 +704,10 @@ impl Guild {
}
let lhs = self.members.get(&lhs_id)?
- .highest_role_info()
+ .highest_role_info(&cache)
.unwrap_or((RoleId(0), 0));
let rhs = self.members.get(&rhs_id)?
- .highest_role_info()
+ .highest_role_info(&cache)
.unwrap_or((RoleId(0), 0));
// If LHS and RHS both have no top position or have the same role ID,
@@ -754,12 +761,12 @@ impl Guild {
///
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [Manage Guild]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_GUILD
- pub fn invites(&self) -> Result<Vec<RichInvite>> {
+ pub fn invites(&self, context: &Context) -> Result<Vec<RichInvite>> {
#[cfg(feature = "cache")]
{
let req = Permissions::MANAGE_GUILD;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -790,7 +797,9 @@ impl Guild {
/// [`Guild`]: ../guild/struct.Guild.html
/// [`Member`]: struct.Member.html
#[inline]
- pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { self.id.member(user_id) }
+ pub fn member<U: Into<UserId>>(&self, context: &Context, user_id: U) -> Result<Member> {
+ self.id.member(&context, user_id)
+ }
/// Gets a list of the guild's members.
///
@@ -1339,12 +1348,12 @@ impl Guild {
/// [`GuildPrune`]: struct.GuildPrune.html
/// [`Member`]: struct.Member.html
/// [Kick Members]: ../permissions/struct.Permissions.html#associatedconstant.KICK_MEMBERS
- pub fn prune_count(&self, days: u16) -> Result<GuildPrune> {
+ pub fn prune_count(&self, context: &Context, days: u16) -> Result<GuildPrune> {
#[cfg(feature = "cache")]
{
let req = Permissions::KICK_MEMBERS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -1374,7 +1383,7 @@ impl Guild {
/// [`utils::shard_id`]: ../../utils/fn.shard_id.html
#[cfg(all(feature = "cache", feature = "utils"))]
#[inline]
- pub fn shard_id(&self) -> u64 { self.id.shard_id() }
+ pub fn shard_id(&self, cache: &Arc<RwLock<Cache>>) -> u64 { self.id.shard_id(&cache) }
/// Returns the Id of the shard associated with the guild.
///
@@ -1432,12 +1441,12 @@ impl Guild {
/// [`GuildPrune`]: struct.GuildPrune.html
/// [`Member`]: struct.Member.html
/// [Kick Members]: ../permissions/struct.Permissions.html#associatedconstant.KICK_MEMBERS
- pub fn start_prune(&self, days: u16) -> Result<GuildPrune> {
+ pub fn start_prune(&self, context: &Context, days: u16) -> Result<GuildPrune> {
#[cfg(feature = "cache")]
{
let req = Permissions::KICK_MEMBERS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -1457,12 +1466,12 @@ impl Guild {
/// [`ModelError::InvalidPermissions`]: ../error/enum.Error.html#variant.InvalidPermissions
/// [`User`]: ../user/struct.User.html
/// [Ban Members]: ../permissions/struct.Permissions.html#associatedconstant.BAN_MEMBERS
- pub fn unban<U: Into<UserId>>(&self, user_id: U) -> Result<()> {
+ pub fn unban<U: Into<UserId>>(&self, context: &Context, user_id: U) -> Result<()> {
#[cfg(feature = "cache")]
{
let req = Permissions::BAN_MEMBERS;
- if !self.has_perms(req) {
+ if !self.has_perms(&context.cache, req) {
return Err(Error::Model(ModelError::InvalidPermissions(req)));
}
}
@@ -1503,11 +1512,9 @@ impl Guild {
///
/// struct Handler;
///
- /// use serenity::CACHE;
- ///
/// impl EventHandler for Handler {
- /// fn message(&self, _: Context, msg: Message) {
- /// if let Some(arc) = msg.guild_id.unwrap().to_guild_cached() {
+ /// fn message(&self, ctx: Context, msg: Message) {
+ /// if let Some(arc) = msg.guild_id.unwrap().to_guild_cached(&ctx.cache) {
/// if let Some(role) = arc.read().role_by_name("role_name") {
/// println!("{:?}", role);
/// }
diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs
index 6276db2..8b1be58 100644
--- a/src/model/guild/partial_guild.rs
+++ b/src/model/guild/partial_guild.rs
@@ -1,6 +1,8 @@
-use crate::model::prelude::*;
+use crate::{model::prelude::*};
use super::super::utils::{deserialize_emojis, deserialize_roles};
+#[cfg(feature = "client")]
+use crate::client::Context;
#[cfg(feature = "model")]
use crate::builder::{EditGuild, EditMember, EditRole};
@@ -333,7 +335,9 @@ impl PartialGuild {
///
/// [`Guild`]: struct.Guild.html
/// [`Member`]: struct.Member.html
- pub fn member<U: Into<UserId>>(&self, user_id: U) -> Result<Member> { self.id.member(user_id) }
+ pub fn member<U: Into<UserId>>(&self, context: &Context, user_id: U) -> Result<Member> {
+ self.id.member(&context, user_id)
+ }
/// Gets a list of the guild's members.
///
@@ -380,7 +384,7 @@ impl PartialGuild {
/// [`utils::shard_id`]: ../../utils/fn.shard_id.html
#[cfg(all(feature = "cache", feature = "utils"))]
#[inline]
- pub fn shard_id(&self) -> u64 { self.id.shard_id() }
+ pub fn shard_id(&self, context: &Context) -> u64 { self.id.shard_id(&context.cache) }
/// Returns the Id of the shard associated with the guild.
///
@@ -465,8 +469,6 @@ impl PartialGuild {
///
/// struct Handler;
///
- /// use serenity::CACHE;
- ///
/// impl EventHandler for Handler {
/// fn message(&self, _: Context, msg: Message) {
/// let guild = msg.guild_id.unwrap().to_partial_guild().unwrap();
diff --git a/src/model/guild/role.rs b/src/model/guild/role.rs
index b68803b..404cfcf 100644
--- a/src/model/guild/role.rs
+++ b/src/model/guild/role.rs
@@ -6,10 +6,10 @@ use crate::builder::EditRole;
#[cfg(all(feature = "cache", feature = "model"))]
use crate::internal::prelude::*;
#[cfg(all(feature = "cache", feature = "model"))]
-use crate::{CACHE, Cache, http};
+use crate::{cache::Cache, http};
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
-use std::str::FromStr;
+use crate::cache::FromStrAndCache;
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
use crate::model::misc::RoleParseError;
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
@@ -75,7 +75,9 @@ impl Role {
/// [Manage Roles]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_ROLES
#[cfg(feature = "cache")]
#[inline]
- pub fn delete(&self) -> Result<()> { http::delete_role(self.find_guild()?.0, self.id.0) }
+ pub fn delete(&self, cache: &Arc<RwLock<Cache>>) -> Result<()> {
+ http::delete_role(self.find_guild(&cache)?.0, self.id.0)
+ }
/// Edits a [`Role`], optionally setting its new fields.
///
@@ -85,9 +87,9 @@ impl Role {
///
/// Make a role hoisted:
///
- /// ```rust,no_run
+ /// ```rust,ignore
/// # use serenity::model::id::RoleId;
- /// # let role = RoleId(7).to_role_cached().unwrap();
+ /// # let role = RoleId(7).to_role_cached(&cache).unwrap();
/// // assuming a `role` has already been bound
//
/// role.edit(|mut r| {
@@ -100,8 +102,8 @@ impl Role {
/// [`Role`]: struct.Role.html
/// [Manage Roles]: ../permissions/struct.Permissions.html#associatedconstant.MANAGE_ROLES
#[cfg(all(feature = "builder", feature = "cache"))]
- pub fn edit<F: FnOnce(EditRole) -> EditRole>(&self, f: F) -> Result<Role> {
- self.find_guild()
+ pub fn edit<F: FnOnce(EditRole) -> EditRole>(&self, cache: &Arc<RwLock<Cache>>, f: F) -> Result<Role> {
+ self.find_guild(&cache)
.and_then(|guild_id| guild_id.edit_role(self.id, f))
}
@@ -114,8 +116,8 @@ impl Role {
///
/// [`ModelError::GuildNotFound`]: ../error/enum.Error.html#variant.GuildNotFound
#[cfg(feature = "cache")]
- pub fn find_guild(&self) -> Result<GuildId> {
- for guild in CACHE.read().guilds.values() {
+ pub fn find_guild(&self, cache: &Arc<RwLock<Cache>>) -> Result<GuildId> {
+ for guild in cache.read().guilds.values() {
let guild = guild.read();
if guild.roles.contains_key(&RoleId(self.id.0)) {
@@ -178,12 +180,12 @@ impl RoleId {
///
/// [`Role`]: ../guild/struct.Role.html
#[cfg(feature = "cache")]
- pub fn to_role_cached(self) -> Option<Role> {
- self._to_role_cached(&CACHE)
+ pub fn to_role_cached(self, cache: &Arc<RwLock<Cache>>) -> Option<Role> {
+ self._to_role_cached(&cache)
}
#[cfg(feature = "cache")]
- pub(crate) fn _to_role_cached(self, cache: &RwLock<Cache>) -> Option<Role> {
+ pub(crate) fn _to_role_cached(self, cache: &Arc<RwLock<Cache>>) -> Option<Role> {
for guild in cache.read().guilds.values() {
let guild = guild.read();
@@ -211,12 +213,12 @@ impl<'a> From<&'a Role> for RoleId {
}
#[cfg(all(feature = "cache", feature = "model", feature = "utils"))]
-impl FromStr for Role {
+impl FromStrAndCache for Role {
type Err = RoleParseError;
- fn from_str(s: &str) -> StdResult<Self, Self::Err> {
+ fn from_str(cache: &Arc<RwLock<Cache>>, s: &str) -> StdResult<Self, Self::Err> {
match parse_role(s) {
- Some(x) => match RoleId(x).to_role_cached() {
+ Some(x) => match RoleId(x).to_role_cached(&cache) {
Some(role) => Ok(role),
_ => Err(RoleParseError::NotPresentInCache),
},