Skip to content

Commit

Permalink
Use feature flags instead of command line arguments (#23)
Browse files Browse the repository at this point in the history
  • Loading branch information
banocean authored Jan 9, 2024
1 parent f20897d commit ce882b2
Show file tree
Hide file tree
Showing 19 changed files with 198 additions and 80 deletions.
8 changes: 5 additions & 3 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ jobs:
linter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Update toolchain
run: rustup update stable
- name: Check
run: cargo check
run: cargo check --features all
- name: Tests
run: cargo test
run: cargo test --features all
21 changes: 15 additions & 6 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
twilight-gateway = "0.15"
twilight-gateway = { version = "0.15", optional = true }
twilight-model = "0.15"
twilight-http = "0.15"
twilight-util = { version = "0.15", features = ["full"] }
Expand All @@ -24,13 +24,22 @@ mongodb = "2.1.0"
redis = "0.21.6"

tokio-tungstenite = { version = "0.17.1", features = ["native-tls"] }
hyper = { version = "0.14.20", features = ["full"] }
hyper = { version = "0.14.20", optional = true }

ed25519-dalek = "1.0.1"
humantime = "2.1.0"
dotenv = "0.15.0"
chrono = "0.4.19"

ed25519-dalek = { version = "1.0.1", optional = true }
dotenv = "0.15.0"
reqwest = "0.11.9"
regex = "1.5.4"
regex = { version = "1.5.4", optional = true }
dashmap = "5.2.0"
hex = "0.4.3"
hex = { version = "0.4.3", optional = true }

[features]
all = ["custom-clients", "tasks", "http-interactions", "gateway"]
custom-clients = []
tasks = []
http-interactions = ["dep:hyper", "dep:hex", "dep:ed25519-dalek", "hyper/full"]
gateway = ["dep:regex", "dep:twilight-gateway"]

17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Custom
A user-friendly Discord bot that simplifies server management, automates tasks, and enhances engagement. Enjoy seamless moderation, level-based rewards, and a straightforward setup process.
## Compilation
```bash
cargo build --release --features all
./target/release/custom
```
## Feature flags
Everything that is separated by feature flags can be run separately from processes with other features, as long as they are connected to the same MongoDB and Redis databases.

| Name | Description |
| ------------------- |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `all` | Enables all the feature flags listed below |
| `custom-bots` | Listens for events on bot accounts set by users |
| `gateway` | Listens for events on a main account ([Gateway connection]([https://discord.com/developers/docs/topics/gateway#connections](https://discord.com/developers/docs/topics/gateway#connections))) |
| `http-interactions` | Runs HTTP server on port 80 that listen for interactions sent by discord ([Receiving interactions]([https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction](https://discord.com/developers/docs/interactions/receiving-and-responding#receiving-an-interaction))) |
| `tasks` | Runs tasks scheduler (handles actions like removing roles from temporary muted users)
11 changes: 11 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

fn main() {
#[cfg(not(feature = "http-interactions"))]
#[cfg(not(feature = "custom-clients"))]
#[cfg(not(feature = "gateway"))]
#[cfg(not(feature = "tasks"))]
{
eprintln!("You need to specify features before compiling code\n\tTo compile everything try using `cargo build --features all`");
std::process::exit(1);
}
}
3 changes: 2 additions & 1 deletion src/commands/moderation/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,9 @@ use twilight_model::id::Id;
use twilight_model::id::marker::{GenericMarker, GuildMarker, RoleMarker, UserMarker};
use crate::commands::ResponseData;
use crate::context::Context;
use crate::{extract, get_option, get_required_option, RedisConnection};
use crate::{extract, get_option, get_required_option};
use crate::commands::context::{InteractionContext, InteractionHelpers};
use crate::database::redis::RedisConnection;
use crate::models::case::{Case, CaseActionType};
use crate::models::config::GuildConfig;
use crate::models::config::moderation::MuteMode;
Expand Down
31 changes: 26 additions & 5 deletions src/context.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
use crate::{database::{mongodb::MongoDBConnection, redis::RedisConnection}, links::ScamLinks, bucket::Bucket, application::Application};
use crate::{all_macro, application::Application, database::{mongodb::MongoDBConnection, redis::RedisConnection}};

all_macro!(
cfg(feature = "gateway");
use crate::bucket::Bucket;
use crate::links::ScamLinks;
);

pub struct Context {
pub application: Application,
pub mongodb: MongoDBConnection,
pub redis: RedisConnection,
#[cfg(feature = "gateway")]
pub scam_domains: ScamLinks,
pub bucket: Bucket
#[cfg(feature = "gateway")]
pub bucket: Bucket,
}

impl Context {
Expand All @@ -16,13 +24,26 @@ impl Context {
let mongodb = MongoDBConnection::connect(mongodb_url).await.unwrap();
let redis = RedisConnection::connect(redis_url).unwrap();

let scam_domains = ScamLinks::new().await.expect("Cannot load scam links manager");
#[cfg(feature = "gateway")]
let scam_domains = ScamLinks::new()
.await
.expect("Cannot load scam links manager");
#[cfg(feature = "gateway")]
scam_domains.connect();

#[cfg(feature = "gateway")]
let bucket: Bucket = Default::default();

let application = Application::new();

Self { mongodb, redis, scam_domains, bucket, application }
Self {
mongodb,
redis,
#[cfg(feature = "gateway")]
scam_domains,
#[cfg(feature = "gateway")]
bucket,
application,
}
}
}
}
9 changes: 8 additions & 1 deletion src/database/mongodb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ use std::sync::Arc;
use dashmap::DashMap;
use futures_util::TryStreamExt;
use mongodb::{Client, Collection, Database};
use mongodb::bson::{DateTime, doc};
use mongodb::bson::doc;
#[cfg(feature = "tasks")]
use mongodb::bson::DateTime;
use twilight_model::channel::message::Embed;
use twilight_model::id::Id;
use twilight_model::id::marker::{ChannelMarker, GuildMarker, UserMarker};
#[cfg(any(feature = "tasks", feature = "custom-clients"))]
use crate::gateway::clients::ClientData;
use crate::models::case::Case;
use crate::models::config::GuildConfig;
Expand All @@ -19,6 +22,7 @@ pub struct MongoDBConnection {
pub database: Database,
pub cases: Collection<Case>,
pub configs: Collection<GuildConfig>,
#[cfg(any(feature = "tasks", feature = "custom-clients"))]
pub clients: Collection<ClientData>,
pub tasks: Collection<Task>,
pub configs_cache: Arc<DashMap<Id<GuildMarker>, GuildConfig>>
Expand All @@ -32,6 +36,7 @@ impl MongoDBConnection {
let db = client.database("custom");
let configs = db.collection::<GuildConfig>("configs");
let cases = db.collection("cases");
#[cfg(any(feature = "tasks", feature = "custom-clients"))]
let clients = db.collection("clients");
let tasks = db.collection("tasks");

Expand All @@ -40,6 +45,7 @@ impl MongoDBConnection {
database: db,
cases,
client,
#[cfg(any(feature = "tasks", feature = "custom-clients"))]
clients,
configs,
tasks
Expand Down Expand Up @@ -111,6 +117,7 @@ impl MongoDBConnection {
self.tasks.insert_one(task, None).await.map(|_| ()).map_err(Error::from)
}

#[cfg(feature = "tasks")]
pub async fn get_and_delete_future_tasks(&self, after: u64) -> Result<Vec<Task>, Error> {
let time = DateTime::from_millis(DateTime::now().timestamp_millis() + after as i64);
let filter = doc! { "execute_at": { "$lt": time } };
Expand Down
2 changes: 1 addition & 1 deletion src/events/automod/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use twilight_http::Client;
use twilight_model::channel::Message;
use twilight_model::id::Id;
use twilight_model::id::marker::GuildMarker;
use crate::Bucket;
use crate::bucket::Bucket;
use crate::models::config::GuildConfig;
use crate::models::config::automod::actions::{Timeout, Action};
use crate::utils::avatars::get_avatar_url;
Expand Down
3 changes: 2 additions & 1 deletion src/events/automod/checks.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::models::config::automod::checks::{CapsLock, Check, Invites, Regex, TextLines};
use crate::{ok_or_skip_without_clone, ScamLinks};
use crate::ok_or_skip_without_clone;
use crate::links::ScamLinks;

impl Check {
pub async fn is_matching(&self, message_content: &String, scam_domains: &ScamLinks) -> Result<bool, ()> {
Expand Down
3 changes: 1 addition & 2 deletions src/events/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ use twilight_http::Client;
use twilight_model::gateway::payload::incoming::{GuildCreate, GuildUpdate};
use twilight_model::id::Id;
use twilight_model::id::marker::GuildMarker;
use crate::database::redis::PartialGuild;
use crate::RedisConnection;
use crate::database::redis::{PartialGuild, RedisConnection};

pub async fn fetch_and_set(
redis: &RedisConnection,
Expand Down
2 changes: 1 addition & 1 deletion src/events/restore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub mod mutes {
pub mod bans {
use mongodb::bson::doc;
use twilight_model::gateway::payload::incoming::BanRemove;
use crate::MongoDBConnection;
use crate::database::mongodb::MongoDBConnection;

pub async fn run(event: BanRemove, mongodb: &MongoDBConnection) -> Result<(), ()> {
mongodb.tasks.delete_one(doc! {
Expand Down
22 changes: 13 additions & 9 deletions src/gateway/clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,26 @@ use mongodb::bson::doc;
use twilight_model::id::Id;
use twilight_model::id::marker::ApplicationMarker;
use serde::{Serialize, Deserialize};
use async_trait::async_trait;
use tokio::task::JoinHandle;
use twilight_http::Client;
use crate::context::Context;
use crate::MongoDBConnection;
use crate::utils::errors::Error;
use crate::database::mongodb::MongoDBConnection;
#[cfg(any(feature = "gateway", feature = "custom-clients"))]
use crate::gateway::shard::connect_shards;
use crate::utils::errors::Error;

pub type DiscordClients = Arc<DashMap<Id<ApplicationMarker>, Arc<Client>>>;

#[async_trait]
pub trait LoadDiscordClients {
async fn load(
mongodb: &MongoDBConnection
) -> Result<DiscordClients, Error>;

#[cfg(any(feature = "gateway", feature = "custom-clients"))]
fn start(
&self,
context: Arc<Context>
);
) -> Vec<JoinHandle<()>>;
}

#[derive(Serialize, Deserialize, Clone)]
Expand All @@ -32,7 +33,6 @@ pub struct ClientData {
pub token: String,
}

#[async_trait]
impl LoadDiscordClients for DiscordClients {
async fn load(
mongodb: &MongoDBConnection
Expand All @@ -50,15 +50,19 @@ impl LoadDiscordClients for DiscordClients {
Ok(Arc::new(DashMap::from_iter(clients)))
}


#[cfg(any(feature = "gateway", feature = "custom-clients"))]
fn start(
&self,
context: Arc<Context>
) {
) -> Vec<JoinHandle<()>> {
let mut clients = vec![];
for value in self.iter() {
tokio::spawn(connect_shards(
clients.push(tokio::spawn(connect_shards(
(value.key().to_string(), value.to_owned()),
context.to_owned()
));
)));
}
clients
}
}
2 changes: 2 additions & 0 deletions src/gateway/mod.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
#[cfg(any(feature = "tasks", feature = "custom-clients"))]
pub mod clients;
#[cfg(any(feature = "gateway", feature = "custom-clients"))]
pub mod shard;
3 changes: 1 addition & 2 deletions src/links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ impl ScamLinks {

#[cfg(test)]
mod tests {
use crate::ScamLinks;
use crate::links::ScamLinks;

#[tokio::test]
async fn test_contains_method() {
Expand All @@ -92,5 +92,4 @@ mod tests {
false
);
}

}
Loading

0 comments on commit ce882b2

Please sign in to comment.