diff --git a/src/model/guild/mod.rs b/src/model/guild/mod.rs index 5ffbf4efb43..a6900039e92 100644 --- a/src/model/guild/mod.rs +++ b/src/model/guild/mod.rs @@ -1038,6 +1038,41 @@ impl Guild { /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] pub fn webhooks(&self) -> Result> { 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 { diff --git a/src/model/guild/partial_guild.rs b/src/model/guild/partial_guild.rs index 799f6b6db76..84d48d39ea7 100644 --- a/src/model/guild/partial_guild.rs +++ b/src/model/guild/partial_guild.rs @@ -450,4 +450,38 @@ impl PartialGuild { /// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html #[inline] pub fn webhooks(&self) -> Result> { 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) + } }