Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for Auto Moderation feature #2035

Merged
merged 18 commits into from Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
131 changes: 131 additions & 0 deletions src/builder/create_automod_rule.rs
@@ -0,0 +1,131 @@
use std::collections::HashMap;

use crate::json::{json, Value};
use crate::model::guild::automod::{Action, EventType, Trigger};
use crate::model::id::{ChannelId, RoleId};

#[derive(Clone, Debug)]
pub struct CreateAutoModRule(pub HashMap<&'static str, Value>);

impl CreateAutoModRule {
/// The display name of the rule.
pub fn name<D: ToString>(&mut self, name: D) -> &mut Self {
self.0.insert("name", Value::from(name.to_string()));

self
}

/// Set the event context the rule should be checked.
pub fn event_type(&mut self, event_type: EventType) -> &mut Self {
self.0.insert("event_type", u8::from(event_type).into());

self
}

/// Set the type of content which can trigger the rule.
pub fn trigger(&mut self, trigger: Trigger) -> &mut Self {
self.0.insert("trigger_type", u8::from(trigger.kind()).into());

match trigger {
Trigger::Keyword(keyword_filter) => {
let value = json!({
"keyword_filter": keyword_filter,
});
self.0.insert("trigger_metadata", value);
},
Trigger::KeywordPresent(presets) => {
let value = json!({
"presets": presets,
});
self.0.insert("trigger_metadata", value);
},
_ => {},
}

self
}

/// Set the actions which will execute when the rule is triggered.
pub fn actions<I>(&mut self, actions: I) -> &mut Self
where
I: IntoIterator<Item = Action>,
{
let actions = actions
.into_iter()
.map(|action| {
let kind = action.kind();
match action {
Action::Alert(channel_id) => {
json!({
"type": kind,
"metadata": {
"channel_id": channel_id.0.to_string(),
},
})
},
Action::Timeout(duration) => {
json!({
"type": kind,
"metadata": {
"duration_seconds": duration,
},
})
},
Action::BlockMessage | Action::Unknown(_) => {
json!({
"type": kind,
})
},
}
})
.collect();

self.0.insert("actions", actions);

self
}

/// Set whether the rule is enabled.
pub fn enabled(&mut self, enabled: bool) -> &mut Self {
self.0.insert("enabled", Value::from(enabled));

self
}

/// Set roles that should not be affected by the rule.
///
/// Maximum of 20.
pub fn exempt_roles<I>(&mut self, roles: I) -> &mut Self
where
I: IntoIterator<Item = RoleId>,
{
let ids = roles.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_roles", ids);

self
}

/// Set channels that should not be affected by the rule.
///
/// Maximum of 50.
pub fn exempt_channels<I>(&mut self, channels: I) -> &mut Self
where
I: IntoIterator<Item = ChannelId>,
{
let ids = channels.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_channels", ids);

self
}
}

impl Default for CreateAutoModRule {
fn default() -> Self {
let mut builder = CreateAutoModRule(HashMap::new());
builder.0.insert("event_type", u8::from(EventType::MessageSend).into());

builder
}
}
122 changes: 122 additions & 0 deletions src/builder/edit_automod_rule.rs
@@ -0,0 +1,122 @@
use std::collections::HashMap;

use crate::json::{json, Value};
use crate::model::guild::automod::{Action, EventType, Trigger};
use crate::model::id::{ChannelId, RoleId};

#[derive(Debug, Default, Clone)]
pub struct EditAutoModRule(pub HashMap<&'static str, Value>);

impl EditAutoModRule {
/// The display name of the rule.
pub fn name<D: ToString>(&mut self, name: D) -> &mut Self {
self.0.insert("name", Value::from(name.to_string()));

self
}

/// Set the event context the rule should be checked.
pub fn event_type(&mut self, event_type: EventType) -> &mut Self {
self.0.insert("event_type", u8::from(event_type).into());

self
}

/// Set the type of content which can trigger the rule.
///
/// **None**: The trigger type can't be edited. Only its values.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

EditAutoModRule is almost a full copy of CreateAutoModRole. Maybe the same type can be used for both? With basically just a small change here: "**Note**: When editing a rule, the trigger type can't be edited. Only its values."

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That can probably said about every Create/Edit builder combination in serenity.

EditAutoModRule doesn't set the trigger_type, only the metadata.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright I guess then let's keep the duplication for consistency lol

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I had the impression the builders come in pairs (create/edit) but it's actually either Create* or Edit*.
I was not looking for a pattern of when to use one or the other.
I rolled a dice and Edit stays.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't looked at this closely, but I will say there's a precedent here. Specifically, CreateInteractionResponseFollowup is used for both creating and editing followup interaction messages. I don't know if there's any other builders that are used for both.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should probably rename to CreateAutoModRole then for consistency

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found a counter-example in EditRole, which is used for both creation and editing of roles. I think this can stay named as is, to not cause further friction.

pub fn trigger(&mut self, trigger: Trigger) -> &mut Self {
match trigger {
Trigger::Keyword(keyword_filter) => {
let value = json!({
"keyword_filter": keyword_filter,
});
self.0.insert("trigger_metadata", value);
},
Trigger::KeywordPresent(presets) => {
let value = json!({
"presets": presets,
});
self.0.insert("trigger_metadata", value);
},
_ => {},
}

self
}

/// Set the actions which will execute when the rule is triggered.
pub fn actions<I>(&mut self, actions: I) -> &mut Self
where
I: IntoIterator<Item = Action>,
{
let actions = actions
.into_iter()
.map(|action| {
let kind = action.kind();
match action {
Action::Alert(channel_id) => {
json!({
"type": kind,
"metadata": {
"channel_id": channel_id.0.to_string(),
},
})
},
Action::Timeout(duration) => {
json!({
"type": kind,
"metadata": {
"duration_seconds": duration,
},
})
},
Action::BlockMessage | Action::Unknown(_) => {
json!({
"type": kind,
})
},
}
})
.collect();

self.0.insert("actions", actions);

self
}

/// Set whether the rule is enabled.
pub fn enabled(&mut self, enabled: bool) -> &mut Self {
self.0.insert("enabled", Value::from(enabled));

self
}

/// Set roles that should not be affected by the rule.
///
/// Maximum of 20.
pub fn exempt_roles<I>(&mut self, roles: I) -> &mut Self
where
I: IntoIterator<Item = RoleId>,
{
let ids = roles.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_roles", ids);

self
}

/// Set channels that should not be affected by the rule.
///
/// Maximum of 50.
pub fn exempt_channels<I>(&mut self, channels: I) -> &mut Self
where
I: IntoIterator<Item = ChannelId>,
{
let ids = channels.into_iter().map(|id| id.0.to_string()).collect();

self.0.insert("exempt_channels", ids);

self
}
}
4 changes: 4 additions & 0 deletions src/builder/mod.rs
Expand Up @@ -14,6 +14,7 @@ mod create_application_command_permission;
mod add_member;
mod bot_auth_parameters;
mod create_allowed_mentions;
mod create_automod_rule;
mod create_components;
mod create_interaction_response;
mod create_interaction_response_followup;
Expand All @@ -23,6 +24,7 @@ mod create_scheduled_event;
mod create_stage_instance;
mod create_sticker;
mod create_thread;
mod edit_automod_rule;
mod edit_channel;
mod edit_guild;
mod edit_guild_welcome_screen;
Expand Down Expand Up @@ -55,6 +57,7 @@ pub use self::create_application_command_permission::{
CreateApplicationCommandPermissionsData,
CreateApplicationCommandsPermissions,
};
pub use self::create_automod_rule::CreateAutoModRule;
pub use self::create_channel::CreateChannel;
pub use self::create_components::{
CreateActionRow,
Expand All @@ -78,6 +81,7 @@ pub use self::create_scheduled_event::CreateScheduledEvent;
pub use self::create_stage_instance::CreateStageInstance;
pub use self::create_sticker::CreateSticker;
pub use self::create_thread::CreateThread;
pub use self::edit_automod_rule::EditAutoModRule;
pub use self::edit_channel::EditChannel;
pub use self::edit_guild::EditGuild;
pub use self::edit_guild_welcome_screen::EditGuildWelcomeScreen;
Expand Down
20 changes: 20 additions & 0 deletions src/client/dispatch.rs
Expand Up @@ -373,6 +373,26 @@ async fn handle_event(
},
);
},
Event::AutoModerationRuleCreate(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_create", async move {
event_handler.auto_moderation_rule_create(context, event.rule).await;
});
},
Event::AutoModerationRuleUpdate(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_update", async move {
event_handler.auto_moderation_rule_update(context, event.rule).await;
});
},
Event::AutoModerationRuleDelete(event) => {
spawn_named("dispatch::event_handler::auto_moderation_rule_delete", async move {
event_handler.auto_moderation_rule_delete(context, event.rule).await;
});
},
Event::AutoModerationActionExecution(event) => {
spawn_named("dispatch::event_handler::auto_moderation_action_execution", async move {
event_handler.auto_moderation_action_execution(context, event.execution).await;
});
},
Event::ChannelCreate(mut event) => {
update(&cache_and_http, &mut event);
match event.channel {
Expand Down
21 changes: 21 additions & 0 deletions src/client/event_handler.rs
Expand Up @@ -7,6 +7,7 @@ use crate::client::bridge::gateway::event::*;
use crate::json::Value;
use crate::model::application::command::CommandPermission;
use crate::model::application::interaction::Interaction;
use crate::model::guild::automod::{ActionExecution, Rule};
use crate::model::prelude::*;

/// The core trait for handling events by serenity.
Expand All @@ -22,6 +23,26 @@ pub trait EventHandler: Send + Sync {
) {
}

/// Dispatched when an auto moderation rule was created.
///
/// Provides said rule's data.
async fn auto_moderation_rule_create(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was updated.
///
/// Provides said rule's data.
async fn auto_moderation_rule_update(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was deleted.
///
/// Provides said rule's data.
async fn auto_moderation_rule_delete(&self, _ctx: Context, _rule: Rule) {}

/// Dispatched when an auto moderation rule was triggered and an action was executed.
///
/// Provides said action execution's data.
async fn auto_moderation_action_execution(&self, _ctx: Context, _execution: ActionExecution) {}

/// Dispatched when the cache has received and inserted all data from
/// guilds.
///
Expand Down