Skip to main content

twilight_http/request/guild/role/
create_role.rs

1#[cfg(not(target_os = "wasi"))]
2use crate::response::{Response, ResponseFuture};
3use crate::{
4    client::Client,
5    error::Error,
6    request::{self, AuditLogReason, Request, TryIntoRequest},
7    routing::Route,
8};
9use serde::Serialize;
10use std::future::IntoFuture;
11use twilight_model::{
12    guild::{Permissions, Role},
13    id::{Id, marker::GuildMarker},
14};
15use twilight_validate::request::{ValidationError, audit_reason as validate_audit_reason};
16
17#[derive(Serialize)]
18struct CreateRoleFields<'a> {
19    #[serde(skip_serializing_if = "Option::is_none")]
20    color: Option<u32>,
21    #[serde(skip_serializing_if = "Option::is_none")]
22    hoist: Option<bool>,
23    #[serde(skip_serializing_if = "Option::is_none")]
24    icon: Option<&'a [u8]>,
25    #[serde(skip_serializing_if = "Option::is_none")]
26    mentionable: Option<bool>,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    name: Option<&'a str>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    permissions: Option<Permissions>,
31    #[serde(skip_serializing_if = "Option::is_none")]
32    unicode_emoji: Option<&'a str>,
33}
34
35/// Create a role in a guild.
36///
37/// # Examples
38///
39/// ```no_run
40/// use twilight_http::Client;
41/// use twilight_model::id::Id;
42///
43/// # #[tokio::main]
44/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
45/// let client = Client::new("my token".to_owned());
46/// let guild_id = Id::new(234);
47///
48/// client
49///     .create_role(guild_id)
50///     .color(0xd90083)
51///     .name("Bright Pink")
52///     .await?;
53/// # Ok(()) }
54/// ```
55#[must_use = "requests must be configured and executed"]
56pub struct CreateRole<'a> {
57    fields: CreateRoleFields<'a>,
58    guild_id: Id<GuildMarker>,
59    http: &'a Client,
60    reason: Result<Option<&'a str>, ValidationError>,
61}
62
63impl<'a> CreateRole<'a> {
64    pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {
65        Self {
66            fields: CreateRoleFields {
67                color: None,
68                hoist: None,
69                icon: None,
70                mentionable: None,
71                name: None,
72                permissions: None,
73                unicode_emoji: None,
74            },
75            guild_id,
76            http,
77            reason: Ok(None),
78        }
79    }
80
81    /// Set the role color.
82    ///
83    /// This must be a valid hexadecimal RGB value. `0x000000` is ignored and
84    /// doesn't count towards the final computed color in the user list. Refer
85    /// to [`COLOR_MAXIMUM`] for the maximum acceptable value.
86    ///
87    /// [`COLOR_MAXIMUM`]: twilight_validate::embed::COLOR_MAXIMUM
88    pub const fn color(mut self, color: u32) -> Self {
89        self.fields.color = Some(color);
90
91        self
92    }
93
94    /// If true, display the role in the members list.
95    pub const fn hoist(mut self, hoist: bool) -> Self {
96        self.fields.hoist = Some(hoist);
97
98        self
99    }
100
101    /// Set the icon of the role.
102    ///
103    /// Only works if the guild has the `ROLE_ICONS` feature.
104    ///
105    /// See [Discord Docs/Image Data].
106    ///
107    /// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data
108    pub const fn icon(mut self, icon: &'a [u8]) -> Self {
109        self.fields.icon = Some(icon);
110
111        self
112    }
113
114    /// If true, the role can be @mentioned (pinged) in chat.
115    pub const fn mentionable(mut self, mentionable: bool) -> Self {
116        self.fields.mentionable = Some(mentionable);
117
118        self
119    }
120
121    /// Set the name of the role.
122    ///
123    /// If none is specified, Discord sets this to `New Role`.
124    pub const fn name(mut self, name: &'a str) -> Self {
125        self.fields.name = Some(name);
126
127        self
128    }
129
130    /// Set the allowed permissions of this role.
131    pub const fn permissions(mut self, permissions: Permissions) -> Self {
132        self.fields.permissions = Some(permissions);
133
134        self
135    }
136
137    /// Set the unicode emoji of a role.
138    pub const fn unicode_emoji(mut self, unicode_emoji: &'a str) -> Self {
139        self.fields.unicode_emoji = Some(unicode_emoji);
140
141        self
142    }
143}
144
145impl<'a> AuditLogReason<'a> for CreateRole<'a> {
146    fn reason(mut self, reason: &'a str) -> Self {
147        self.reason = validate_audit_reason(reason).and(Ok(Some(reason)));
148
149        self
150    }
151}
152
153#[cfg(not(target_os = "wasi"))]
154impl IntoFuture for CreateRole<'_> {
155    type Output = Result<Response<Role>, Error>;
156
157    type IntoFuture = ResponseFuture<Role>;
158
159    fn into_future(self) -> Self::IntoFuture {
160        let http = self.http;
161
162        match self.try_into_request() {
163            Ok(request) => http.request(request),
164            Err(source) => ResponseFuture::error(source),
165        }
166    }
167}
168
169impl TryIntoRequest for CreateRole<'_> {
170    fn try_into_request(self) -> Result<Request, Error> {
171        let mut request = Request::builder(&Route::CreateRole {
172            guild_id: self.guild_id.get(),
173        });
174
175        request = request.json(&self.fields);
176
177        if let Some(reason) = self.reason.map_err(Error::validation)? {
178            request = request.headers(request::audit_header(reason)?);
179        }
180
181        request.build()
182    }
183}