serenity/builder/
create_webhook.rs

1#[cfg(feature = "http")]
2use super::Builder;
3use super::CreateAttachment;
4#[cfg(feature = "http")]
5use crate::http::CacheHttp;
6#[cfg(feature = "http")]
7use crate::internal::prelude::*;
8#[cfg(feature = "http")]
9use crate::model::prelude::*;
10
11/// [Discord docs](https://discord.com/developers/docs/resources/webhook#create-webhook)
12#[derive(Clone, Debug, Serialize)]
13#[must_use]
14pub struct CreateWebhook<'a> {
15    name: String,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    avatar: Option<String>,
18
19    #[serde(skip)]
20    audit_log_reason: Option<&'a str>,
21}
22
23impl<'a> CreateWebhook<'a> {
24    /// Creates a new builder with the given webhook name, leaving all other fields empty.
25    pub fn new(name: impl Into<String>) -> Self {
26        Self {
27            name: name.into(),
28            avatar: None,
29            audit_log_reason: None,
30        }
31    }
32
33    /// Set the webhook's name, replacing the current value as set in [`Self::new`].
34    ///
35    /// This must be between 1-80 characters.
36    pub fn name(mut self, name: impl Into<String>) -> Self {
37        self.name = name.into();
38        self
39    }
40
41    /// Set the webhook's default avatar.
42    pub fn avatar(mut self, avatar: &CreateAttachment) -> Self {
43        self.avatar = Some(avatar.to_base64());
44        self
45    }
46
47    /// Sets the request's audit log reason.
48    pub fn audit_log_reason(mut self, reason: &'a str) -> Self {
49        self.audit_log_reason = Some(reason);
50        self
51    }
52}
53
54#[cfg(feature = "http")]
55#[async_trait::async_trait]
56impl Builder for CreateWebhook<'_> {
57    type Context<'ctx> = ChannelId;
58    type Built = Webhook;
59
60    /// Creates the webhook.
61    ///
62    /// # Errors
63    ///
64    /// If the provided name is less than 2 characters, returns [`ModelError::NameTooShort`]. If it
65    /// is more than 100 characters, returns [`ModelError::NameTooLong`].
66    ///
67    /// Returns a [`Error::Http`] if the current user lacks permission, or if invalid data is
68    /// given.
69    ///
70    /// [`Text`]: ChannelType::Text
71    /// [`News`]: ChannelType::News
72    async fn execute(
73        self,
74        cache_http: impl CacheHttp,
75        ctx: Self::Context<'_>,
76    ) -> Result<Self::Built> {
77        if self.name.len() < 2 {
78            return Err(Error::Model(ModelError::NameTooShort));
79        } else if self.name.len() > 100 {
80            return Err(Error::Model(ModelError::NameTooLong));
81        }
82
83        cache_http.http().create_webhook(ctx, &self, self.audit_log_reason).await
84    }
85}