twilight_http/request/channel/webhook/
create_webhook.rs

1use crate::{
2    client::Client,
3    error::Error,
4    request::{self, AuditLogReason, Request, TryIntoRequest},
5    response::{Response, ResponseFuture},
6    routing::Route,
7};
8use serde::Serialize;
9use std::future::IntoFuture;
10use twilight_model::{
11    channel::Webhook,
12    id::{marker::ChannelMarker, Id},
13};
14use twilight_validate::request::{
15    audit_reason as validate_audit_reason, webhook_username as validate_webhook_username,
16    ValidationError,
17};
18
19#[derive(Serialize)]
20struct CreateWebhookFields<'a> {
21    #[serde(skip_serializing_if = "Option::is_none")]
22    avatar: Option<&'a str>,
23    name: &'a str,
24}
25
26/// Create a webhook in a channel.
27///
28/// # Examples
29///
30/// ```no_run
31/// use twilight_http::Client;
32/// use twilight_model::id::Id;
33///
34/// # #[tokio::main]
35/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
36/// let client = Client::new("my token".to_owned());
37/// let channel_id = Id::new(123);
38///
39/// let webhook = client.create_webhook(channel_id, "Twily Bot").await?;
40/// # Ok(()) }
41/// ```
42#[must_use = "requests must be configured and executed"]
43pub struct CreateWebhook<'a> {
44    channel_id: Id<ChannelMarker>,
45    fields: Result<CreateWebhookFields<'a>, ValidationError>,
46    http: &'a Client,
47    reason: Result<Option<&'a str>, ValidationError>,
48}
49
50impl<'a> CreateWebhook<'a> {
51    pub(crate) fn new(http: &'a Client, channel_id: Id<ChannelMarker>, name: &'a str) -> Self {
52        let fields = Ok(CreateWebhookFields { avatar: None, name }).and_then(|fields| {
53            validate_webhook_username(name)?;
54
55            Ok(fields)
56        });
57
58        Self {
59            channel_id,
60            fields,
61            http,
62            reason: Ok(None),
63        }
64    }
65
66    /// Set the avatar of the webhook.
67    ///
68    /// This must be a Data URI, in the form of
69    /// `data:image/{type};base64,{data}` where `{type}` is the image MIME type
70    /// and `{data}` is the base64-encoded image. See [Discord Docs/Image Data].
71    ///
72    /// [Discord Docs/Image Data]: https://discord.com/developers/docs/reference#image-data
73    pub fn avatar(mut self, avatar: &'a str) -> Self {
74        self.fields = self.fields.map(|mut fields| {
75            fields.avatar = Some(avatar);
76
77            fields
78        });
79
80        self
81    }
82}
83
84impl<'a> AuditLogReason<'a> for CreateWebhook<'a> {
85    fn reason(mut self, reason: &'a str) -> Self {
86        self.reason = validate_audit_reason(reason).and(Ok(Some(reason)));
87
88        self
89    }
90}
91
92impl IntoFuture for CreateWebhook<'_> {
93    type Output = Result<Response<Webhook>, Error>;
94
95    type IntoFuture = ResponseFuture<Webhook>;
96
97    fn into_future(self) -> Self::IntoFuture {
98        let http = self.http;
99
100        match self.try_into_request() {
101            Ok(request) => http.request(request),
102            Err(source) => ResponseFuture::error(source),
103        }
104    }
105}
106
107impl TryIntoRequest for CreateWebhook<'_> {
108    fn try_into_request(self) -> Result<Request, Error> {
109        let fields = self.fields.map_err(Error::validation)?;
110        let mut request = Request::builder(&Route::CreateWebhook {
111            channel_id: self.channel_id.get(),
112        })
113        .json(&fields);
114
115        if let Some(reason) = self.reason.map_err(Error::validation)? {
116            request = request.headers(request::audit_header(reason)?);
117        }
118
119        request.build()
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use std::error::Error;
127
128    #[test]
129    fn test_create_webhook() -> Result<(), Box<dyn Error>> {
130        const CHANNEL_ID: Id<ChannelMarker> = Id::new(1);
131
132        let client = Client::new("token".into());
133
134        {
135            let expected = r#"{"name":"Spidey Bot"}"#;
136            let actual =
137                CreateWebhook::new(&client, CHANNEL_ID, "Spidey Bot").try_into_request()?;
138
139            assert_eq!(Some(expected.as_bytes()), actual.body());
140        }
141
142        {
143            let expected = r#"{"avatar":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI","name":"Spidey Bot"}"#;
144            let actual = CreateWebhook::new(&client, CHANNEL_ID, "Spidey Bot")
145            .avatar(
146                "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI",
147            )
148                .try_into_request()?;
149
150            assert_eq!(Some(expected.as_bytes()), actual.body());
151        }
152
153        Ok(())
154    }
155}