Skip to main content

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