Skip to content

Commit

Permalink
Make role references attainable via name
Browse files Browse the repository at this point in the history
  • Loading branch information
Lakelezz authored and Zeyla Hellyer committed Aug 29, 2017
1 parent 25e91da commit f6fcf32
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/model/guild/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1038,6 +1038,41 @@ impl Guild {
/// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html
#[inline]
pub fn webhooks(&self) -> Result<Vec<Webhook>> { self.id.webhooks() }

/// Obtain a reference to a role by its name.
///
/// **Note**: If two or more roles have the same name, obtained reference will be one of
/// them.
///
/// # Examples
///
/// Obtain a reference to a [`Role`] by its name.
///
/// ```rust,no_run
/// use serenity::model::*;
/// use serenity::prelude::*;
///
/// struct Handler;
///
/// use serenity::CACHE;
///
/// impl EventHandler for Handler {
/// fn on_message(&self, _: Context, msg: Message) {
/// if let Some(arc) = msg.guild_id().unwrap().find() {
/// if let Some(role) = arc.read().unwrap().role_by_name("role_name") {
/// println!("{:?}", role);
/// }
/// }
/// }
/// }
///
/// let mut client = Client::new("token", Handler);
///
/// client.start().unwrap();
/// ```
pub fn role_by_name(&self, role_name: &str) -> Option<&Role> {
self.roles.values().find(|role| role_name == role.name)
}
}

impl<'de> Deserialize<'de> for Guild {
Expand Down
34 changes: 34 additions & 0 deletions src/model/guild/partial_guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -450,4 +450,38 @@ impl PartialGuild {
/// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html
#[inline]
pub fn webhooks(&self) -> Result<Vec<Webhook>> { self.id.webhooks() }

/// Obtain a reference to a role by its name.
///
/// **Note**: If two or more roles have the same name, obtained reference will be one of
/// them.
///
/// # Examples
///
/// Obtain a reference to a [`Role`] by its name.
///
/// ```rust,no_run
/// use serenity::model::*;
/// use serenity::prelude::*;
///
/// struct Handler;
///
/// use serenity::CACHE;
///
/// impl EventHandler for Handler {
/// fn on_message(&self, _: Context, msg: Message) {
/// if let Some(role) =
/// msg.guild_id().unwrap().get().unwrap().role_by_name("role_name") {
/// println!("Obtained role's reference: {:?}", role);
/// }
/// }
/// }
///
/// let mut client = Client::new("token", Handler);
///
/// client.start().unwrap();
/// ```
pub fn role_by_name(&self, role_name: &str) -> Option<&Role> {
self.roles.values().find(|role| role_name == role.name)
}
}

0 comments on commit f6fcf32

Please sign in to comment.