Skip to main content

djs_model/rest/
auto_moderation.rs

1//! Bodies of the [Auto Moderation endpoints](https://docs.discord.com/developers/resources/auto-moderation).
2
3use compact_str::CompactString;
4use serde::Serialize;
5
6use crate::{
7    auto_moderation::{Action, EventType, KeywordPresetType, TriggerMetadata, TriggerType},
8    id::{ChannelId, RoleId},
9};
10
11/// The body of [Create Auto Moderation Rule](https://docs.discord.com/developers/resources/auto-moderation#create-auto-moderation-rule).
12///
13/// Built with one constructor per [`TriggerType`] (D-128), which sets the trigger, the
14/// [`EventType`] it checks and the trigger metadata it requires. The allow list, regular
15/// expressions, [`enabled`](Self::enabled) and the exemptions are set through the public
16/// fields afterwards.
17///
18/// discord.js counterpart: the argument of `AutoModerationRuleManager#create`.
19///
20/// # Examples
21///
22/// ```
23/// use djs_model::{auto_moderation::Action, rest::CreateAutoModerationRule};
24///
25/// let mut body = CreateAutoModerationRule::keyword(
26///     "No spoilers",
27///     ["*spoiler*"],
28///     [Action::block_message()],
29/// );
30/// body.enabled = Some(true);
31/// body.trigger_metadata.allow_list = vec!["spoilerfree".into()];
32/// assert_eq!(
33///     serde_json::to_string(&body)?,
34///     r#"{"name":"No spoilers","event_type":1,"trigger_type":1,"trigger_metadata":{"keyword_filter":["*spoiler*"],"allow_list":["spoilerfree"]},"actions":[{"type":1}],"enabled":true}"#
35/// );
36/// # Ok::<(), serde_json::Error>(())
37/// ```
38#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
39#[non_exhaustive]
40pub struct CreateAutoModerationRule {
41    /// The rule's name.
42    pub name: CompactString,
43    /// What the rule checks: sent messages, or member profiles for `MemberProfile` rules.
44    pub event_type: EventType,
45    /// How the rule detects violations. Each guild may have up to 6 `Keyword` rules and 1 of
46    /// every other type.
47    pub trigger_type: TriggerType,
48    /// The settings of the trigger; only the fields of [`trigger_type`](Self::trigger_type)
49    /// apply. Left out of the request when empty (`Spam` rules have none).
50    #[serde(skip_serializing_if = "is_empty")]
51    pub trigger_metadata: TriggerMetadata,
52    /// What happens when the rule triggers.
53    pub actions: Vec<Action>,
54    /// Whether the rule is enabled; Discord's default is disabled.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub enabled: Option<bool>,
57    /// Roles the rule does not apply to (up to 20).
58    #[serde(skip_serializing_if = "Vec::is_empty")]
59    pub exempt_roles: Vec<RoleId>,
60    /// Channels the rule does not apply to (up to 50).
61    #[serde(skip_serializing_if = "Vec::is_empty")]
62    pub exempt_channels: Vec<ChannelId>,
63}
64
65/// Whether trigger metadata has nothing set, so it can be left out of the request.
66fn is_empty(metadata: &TriggerMetadata) -> bool {
67    *metadata == TriggerMetadata::default()
68}
69
70impl CreateAutoModerationRule {
71    /// The shared part of the constructors.
72    fn with(
73        name: impl Into<CompactString>,
74        event_type: EventType,
75        trigger_type: TriggerType,
76        trigger_metadata: TriggerMetadata,
77        actions: impl IntoIterator<Item = Action>,
78    ) -> Self {
79        Self {
80            name: name.into(),
81            event_type,
82            trigger_type,
83            trigger_metadata,
84            actions: actions.into_iter().collect(),
85            enabled: None,
86            exempt_roles: Vec::new(),
87            exempt_channels: Vec::new(),
88        }
89    }
90
91    /// A rule that triggers on messages containing one of `keywords` (up to 1000, 60
92    /// characters each; `*` at the start or end matches a prefix or suffix). Add
93    /// [`regex_patterns`](TriggerMetadata::regex_patterns) and an
94    /// [`allow_list`](TriggerMetadata::allow_list) through
95    /// [`trigger_metadata`](Self::trigger_metadata).
96    ///
97    /// discord.js counterpart: `AutoModerationRuleCreateOptions` with `AutoModerationRuleTriggerType.Keyword`.
98    #[must_use]
99    pub fn keyword(
100        name: impl Into<CompactString>,
101        keywords: impl IntoIterator<Item = impl Into<CompactString>>,
102        actions: impl IntoIterator<Item = Action>,
103    ) -> Self {
104        let metadata = TriggerMetadata {
105            keyword_filter: keywords.into_iter().map(Into::into).collect(),
106            ..TriggerMetadata::default()
107        };
108        Self::with(
109            name,
110            EventType::MessageSend,
111            TriggerType::Keyword,
112            metadata,
113            actions,
114        )
115    }
116
117    /// A rule that triggers on messages Discord considers generic spam.
118    ///
119    /// discord.js counterpart: `AutoModerationRuleCreateOptions` with `AutoModerationRuleTriggerType.Spam`.
120    #[must_use]
121    pub fn spam(name: impl Into<CompactString>, actions: impl IntoIterator<Item = Action>) -> Self {
122        Self::with(
123            name,
124            EventType::MessageSend,
125            TriggerType::Spam,
126            TriggerMetadata::default(),
127            actions,
128        )
129    }
130
131    /// A rule that triggers on messages containing words from Discord's predefined word
132    /// lists. Exceptions go into the [`allow_list`](TriggerMetadata::allow_list) (up to 1000).
133    ///
134    /// discord.js counterpart: `AutoModerationRuleCreateOptions` with `AutoModerationRuleTriggerType.KeywordPreset`.
135    #[must_use]
136    pub fn keyword_preset(
137        name: impl Into<CompactString>,
138        presets: impl IntoIterator<Item = KeywordPresetType>,
139        actions: impl IntoIterator<Item = Action>,
140    ) -> Self {
141        let metadata = TriggerMetadata {
142            presets: presets.into_iter().collect(),
143            ..TriggerMetadata::default()
144        };
145        Self::with(
146            name,
147            EventType::MessageSend,
148            TriggerType::KeywordPreset,
149            metadata,
150            actions,
151        )
152    }
153
154    /// A rule that triggers on messages mentioning more than `limit` unique users and roles
155    /// (up to 50). Enable
156    /// [`mention_raid_protection_enabled`](TriggerMetadata::mention_raid_protection_enabled)
157    /// to also detect mention raids.
158    ///
159    /// discord.js counterpart: `AutoModerationRuleCreateOptions` with `AutoModerationRuleTriggerType.MentionSpam`.
160    #[must_use]
161    pub fn mention_spam(
162        name: impl Into<CompactString>,
163        limit: u8,
164        actions: impl IntoIterator<Item = Action>,
165    ) -> Self {
166        let metadata = TriggerMetadata {
167            mention_total_limit: Some(limit),
168            ..TriggerMetadata::default()
169        };
170        Self::with(
171            name,
172            EventType::MessageSend,
173            TriggerType::MentionSpam,
174            metadata,
175            actions,
176        )
177    }
178
179    /// A rule that triggers when a member's profile contains one of `keywords`, checked when
180    /// they edit it. The keywords work as for [`keyword`](Self::keyword).
181    ///
182    /// discord.js counterpart: `AutoModerationRuleCreateOptions` with `AutoModerationRuleTriggerType.MemberProfile`.
183    #[must_use]
184    pub fn member_profile(
185        name: impl Into<CompactString>,
186        keywords: impl IntoIterator<Item = impl Into<CompactString>>,
187        actions: impl IntoIterator<Item = Action>,
188    ) -> Self {
189        let metadata = TriggerMetadata {
190            keyword_filter: keywords.into_iter().map(Into::into).collect(),
191            ..TriggerMetadata::default()
192        };
193        Self::with(
194            name,
195            EventType::MemberUpdate,
196            TriggerType::MemberProfile,
197            metadata,
198            actions,
199        )
200    }
201}
202
203/// The body of [Modify Auto Moderation Rule](https://docs.discord.com/developers/resources/auto-moderation#modify-auto-moderation-rule).
204///
205/// Every field is optional; the trigger type cannot be changed. Lists replace the rule's
206/// lists, so pass complete ones (an empty list clears it).
207///
208/// discord.js counterpart: the argument of `AutoModerationRule#edit`,
209/// `AutoModerationRuleManager#edit`.
210///
211/// # Examples
212///
213/// ```
214/// use djs_model::{auto_moderation::Action, rest::ModifyAutoModerationRule};
215///
216/// let mut body = ModifyAutoModerationRule::default();
217/// body.enabled = Some(false);
218/// body.actions = Some(vec![Action::block_message(), Action::timeout(60)]);
219/// assert_eq!(
220///     serde_json::to_string(&body)?,
221///     r#"{"actions":[{"type":1},{"type":3,"metadata":{"duration_seconds":60}}],"enabled":false}"#
222/// );
223/// # Ok::<(), serde_json::Error>(())
224/// ```
225#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
226#[non_exhaustive]
227pub struct ModifyAutoModerationRule {
228    /// The new name.
229    #[serde(skip_serializing_if = "Option::is_none")]
230    pub name: Option<CompactString>,
231    /// The new event type.
232    #[serde(skip_serializing_if = "Option::is_none")]
233    pub event_type: Option<EventType>,
234    /// The new trigger settings. Start from the rule's current
235    /// [`trigger_metadata`](crate::auto_moderation::Rule::trigger_metadata) to keep the
236    /// fields you do not change.
237    #[serde(skip_serializing_if = "Option::is_none")]
238    pub trigger_metadata: Option<TriggerMetadata>,
239    /// The new actions.
240    #[serde(skip_serializing_if = "Option::is_none")]
241    pub actions: Option<Vec<Action>>,
242    /// Whether the rule is enabled.
243    #[serde(skip_serializing_if = "Option::is_none")]
244    pub enabled: Option<bool>,
245    /// The new exempt roles (up to 20).
246    #[serde(skip_serializing_if = "Option::is_none")]
247    pub exempt_roles: Option<Vec<RoleId>>,
248    /// The new exempt channels (up to 50).
249    #[serde(skip_serializing_if = "Option::is_none")]
250    pub exempt_channels: Option<Vec<ChannelId>>,
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use crate::auto_moderation::{Action, KeywordPresetType};
257
258    #[test]
259    fn constructors_set_the_trigger() {
260        let json = |body: &CreateAutoModerationRule| serde_json::to_string(body).unwrap();
261        assert_eq!(
262            json(&CreateAutoModerationRule::spam(
263                "Spam",
264                [Action::block_message()]
265            )),
266            r#"{"name":"Spam","event_type":1,"trigger_type":3,"actions":[{"type":1}]}"#
267        );
268        assert_eq!(
269            json(&CreateAutoModerationRule::keyword_preset(
270                "Slurs",
271                [KeywordPresetType::Slurs],
272                [Action::block_message()]
273            )),
274            r#"{"name":"Slurs","event_type":1,"trigger_type":4,"trigger_metadata":{"presets":[3]},"actions":[{"type":1}]}"#
275        );
276        let mut mentions = CreateAutoModerationRule::mention_spam(
277            "Mentions",
278            10,
279            [Action::block_message(), Action::timeout(60)],
280        );
281        mentions.trigger_metadata.mention_raid_protection_enabled = true;
282        assert_eq!(
283            json(&mentions),
284            r#"{"name":"Mentions","event_type":1,"trigger_type":5,"trigger_metadata":{"mention_total_limit":10,"mention_raid_protection_enabled":true},"actions":[{"type":1},{"type":3,"metadata":{"duration_seconds":60}}]}"#
285        );
286        assert_eq!(
287            json(&CreateAutoModerationRule::member_profile(
288                "Names",
289                ["*admin*"],
290                [Action::block_member_interaction()]
291            )),
292            r#"{"name":"Names","event_type":2,"trigger_type":6,"trigger_metadata":{"keyword_filter":["*admin*"]},"actions":[{"type":4}]}"#
293        );
294    }
295}