Skip to main content

djs_model/
auto_moderation.rs

1//! [Auto Moderation](https://docs.discord.com/developers/resources/auto-moderation): rules that
2//! block, flag or time out content automatically.
3
4use compact_str::CompactString;
5use serde::{Deserialize, Serialize};
6
7use crate::{
8    id::{AutoModerationRuleId, ChannelId, GuildId, RoleId, UserId},
9    macros::int_enum,
10};
11
12/// An [Auto Moderation rule](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-rule-object).
13///
14/// discord.js counterpart: `AutoModerationRule`.
15#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
16#[non_exhaustive]
17#[doc(alias = "AutoModerationRule")]
18pub struct Rule {
19    /// The rule's ID.
20    pub id: AutoModerationRuleId,
21    /// The guild the rule belongs to.
22    pub guild_id: GuildId,
23    /// The rule's name.
24    pub name: CompactString,
25    /// Who created the rule.
26    pub creator_id: UserId,
27    /// What the rule checks: sent messages or member profiles.
28    pub event_type: EventType,
29    /// How the rule detects violations.
30    pub trigger_type: TriggerType,
31    /// The settings of the trigger.
32    pub trigger_metadata: TriggerMetadata,
33    /// What happens when the rule triggers.
34    pub actions: Vec<Action>,
35    /// Whether the rule is enabled.
36    pub enabled: bool,
37    /// Roles the rule does not apply to (up to 20).
38    pub exempt_roles: Vec<RoleId>,
39    /// Channels the rule does not apply to (up to 50).
40    pub exempt_channels: Vec<ChannelId>,
41}
42
43int_enum! {
44    /// [How a rule detects violations](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-rule-object-trigger-types).
45    ///
46    /// discord.js counterpart: `AutoModerationRuleTriggerType`.
47    #[doc(alias = "AutoModerationRuleTriggerType")]
48    pub enum TriggerType: u8 {
49        /// Content contains words from a list of keywords (up to 6 rules per guild).
50        Keyword = 1,
51        /// Content is generic spam (1 rule per guild).
52        Spam = 3,
53        /// Content contains words from Discord's predefined word lists (1 rule per guild).
54        KeywordPreset = 4,
55        /// Content mentions more unique users and roles than allowed (1 rule per guild).
56        MentionSpam = 5,
57        /// A member profile contains words from a list of keywords (1 rule per guild).
58        MemberProfile = 6,
59    }
60}
61
62/// The [settings of a rule's trigger](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-rule-object-trigger-metadata).
63///
64/// Which fields apply depends on the [`TriggerType`]: keywords, regexes and the allow list for
65/// `Keyword` and `MemberProfile`; presets and the allow list for `KeywordPreset`; the mention
66/// settings for `MentionSpam`.
67///
68/// discord.js counterpart: `AutoModerationTriggerMetadata`.
69#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
70#[non_exhaustive]
71pub struct TriggerMetadata {
72    /// Substrings to search for (up to 1000, 60 characters each). Supports `*` wildcards.
73    #[serde(default, skip_serializing_if = "Vec::is_empty")]
74    pub keyword_filter: Vec<CompactString>,
75    /// Rust-flavored regular expressions to match (up to 10, 260 characters each).
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub regex_patterns: Vec<CompactString>,
78    /// Discord's predefined word lists to search for.
79    #[serde(default, skip_serializing_if = "Vec::is_empty")]
80    pub presets: Vec<KeywordPresetType>,
81    /// Substrings that never trigger the rule (up to 100, or 1000 for `KeywordPreset`).
82    #[serde(default, skip_serializing_if = "Vec::is_empty")]
83    pub allow_list: Vec<CompactString>,
84    /// How many unique user and role mentions a message may have (up to 50).
85    #[serde(default, skip_serializing_if = "Option::is_none")]
86    pub mention_total_limit: Option<u8>,
87    /// Whether mention raids are detected automatically.
88    #[serde(default, skip_serializing_if = "core::ops::Not::not")]
89    pub mention_raid_protection_enabled: bool,
90}
91
92int_enum! {
93    /// A [predefined word list](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-rule-object-keyword-preset-types).
94    ///
95    /// discord.js counterpart: `AutoModerationRuleKeywordPresetType`.
96    pub enum KeywordPresetType: u8 {
97        /// Swearing and cursing.
98        Profanity = 1,
99        /// Sexually explicit words.
100        SexualContent = 2,
101        /// Personal insults and hate speech.
102        Slurs = 3,
103    }
104}
105
106int_enum! {
107    /// [What a rule checks](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-rule-object-event-types).
108    ///
109    /// discord.js counterpart: `AutoModerationRuleEventType`.
110    pub enum EventType: u8 {
111        /// A member sends or edits a message.
112        MessageSend = 1,
113        /// A member edits their profile.
114        MemberUpdate = 2,
115    }
116}
117
118/// An [action](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-action-object)
119/// taken when a rule triggers.
120///
121/// discord.js counterpart: `AutoModerationAction`.
122#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
123#[non_exhaustive]
124pub struct Action {
125    /// What the action does.
126    #[serde(rename = "type")]
127    pub kind: ActionType,
128    /// Settings of the action; required for `SendAlertMessage` and `Timeout`.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub metadata: Option<ActionMetadata>,
131}
132
133/// Constructors for each [`ActionType`], setting the metadata it requires (D-129).
134///
135/// # Examples
136///
137/// ```
138/// use djs_model::{auto_moderation::Action, id::ChannelId};
139///
140/// let actions = [
141///     Action::block_message_with("Please keep it friendly"),
142///     Action::send_alert_message(ChannelId::new(1)),
143///     Action::timeout(60 * 10),
144/// ];
145/// assert_eq!(
146///     serde_json::to_string(&actions)?,
147///     r#"[{"type":1,"metadata":{"custom_message":"Please keep it friendly"}},{"type":2,"metadata":{"channel_id":"1"}},{"type":3,"metadata":{"duration_seconds":600}}]"#
148/// );
149/// # Ok::<(), serde_json::Error>(())
150/// ```
151impl Action {
152    /// Blocks the message with Discord's default explanation.
153    ///
154    /// discord.js counterpart: an `AutoModerationActionOptions` of type `AutoModerationActionType.BlockMessage`.
155    #[must_use]
156    pub const fn block_message() -> Self {
157        Self {
158            kind: ActionType::BlockMessage,
159            metadata: None,
160        }
161    }
162
163    /// Blocks the message and shows `custom_message` (up to 150 characters) to the member.
164    ///
165    /// discord.js counterpart: an `AutoModerationActionOptions` of type `AutoModerationActionType.BlockMessage`, with `customMessage`.
166    #[must_use]
167    pub fn block_message_with(custom_message: impl Into<CompactString>) -> Self {
168        Self {
169            kind: ActionType::BlockMessage,
170            metadata: Some(ActionMetadata {
171                custom_message: Some(custom_message.into()),
172                ..ActionMetadata::default()
173            }),
174        }
175    }
176
177    /// Logs the content to `channel_id`.
178    ///
179    /// discord.js counterpart: an `AutoModerationActionOptions` of type `AutoModerationActionType.SendAlertMessage`.
180    #[must_use]
181    pub const fn send_alert_message(channel_id: ChannelId) -> Self {
182        Self {
183            kind: ActionType::SendAlertMessage,
184            metadata: Some(ActionMetadata {
185                channel_id: Some(channel_id),
186                duration_seconds: None,
187                custom_message: None,
188            }),
189        }
190    }
191
192    /// Times the member out for `duration_seconds` (up to 2 419 200, four weeks). Only for
193    /// `Keyword` and `MentionSpam` rules; needs the `MODERATE_MEMBERS` permission.
194    ///
195    /// discord.js counterpart: an `AutoModerationActionOptions` of type `AutoModerationActionType.Timeout`.
196    #[must_use]
197    pub const fn timeout(duration_seconds: u32) -> Self {
198        Self {
199            kind: ActionType::Timeout,
200            metadata: Some(ActionMetadata {
201                channel_id: None,
202                duration_seconds: Some(duration_seconds),
203                custom_message: None,
204            }),
205        }
206    }
207
208    /// Stops the member from using text, voice and other interactions.
209    ///
210    /// discord.js counterpart: an `AutoModerationActionOptions` of type `AutoModerationActionType.BlockMemberInteraction`.
211    #[must_use]
212    pub const fn block_member_interaction() -> Self {
213        Self {
214            kind: ActionType::BlockMemberInteraction,
215            metadata: None,
216        }
217    }
218}
219
220int_enum! {
221    /// [What an action does](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-action-object-action-types).
222    ///
223    /// discord.js counterpart: `AutoModerationActionType`.
224    pub enum ActionType: u8 {
225        /// Blocks the message, optionally explaining why to the member.
226        BlockMessage = 1,
227        /// Logs the content to a channel.
228        SendAlertMessage = 2,
229        /// Times the member out (only `Keyword` and `MentionSpam` rules; needs the
230        /// `MODERATE_MEMBERS` permission).
231        Timeout = 3,
232        /// Stops the member from using text, voice and other interactions.
233        BlockMemberInteraction = 4,
234    }
235}
236
237/// The [settings of an action](https://docs.discord.com/developers/resources/auto-moderation#auto-moderation-action-object-action-metadata).
238///
239/// discord.js counterpart: `AutoModerationActionMetadata`.
240#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
241#[non_exhaustive]
242pub struct ActionMetadata {
243    /// Where `SendAlertMessage` logs the content.
244    #[serde(default, skip_serializing_if = "Option::is_none")]
245    pub channel_id: Option<ChannelId>,
246    /// How long `Timeout` times the member out, in seconds (up to 2 419 200, four weeks).
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub duration_seconds: Option<u32>,
249    /// The explanation `BlockMessage` shows to the member (up to 150 characters).
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub custom_message: Option<CompactString>,
252}