Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ futures-util = "0.3"
tokio = "1.43"
tokio-stream = "0.1"

tracing = { version = "0.1", features = ["std"] }
tracing-subscriber = { version = "0.3", features = ["env-filter","registry", "std", "fmt"] }
opentelemetry_sdk = "0.30"
opentelemetry-appender-tracing = "0.30"
tracing-opentelemetry = "0.31"
opentelemetry = { version = "0.30", features = ["trace"] }
opentelemetry-otlp = { version = "0.30", features = ["http-proto", "grpc-tonic"] }

mongodb = "3.2"
redis = { version = "0.29", features = ["aio", "tokio-comp"] }

Expand Down
1 change: 1 addition & 0 deletions src/commands/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ macro_rules! extract {
};
}

#[derive(Debug, Clone)]
pub struct InteractionContext {
pub command_vec: Vec<String>,
pub command_text: String,
Expand Down
10 changes: 8 additions & 2 deletions src/database/mongodb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use mongodb::{Client, Collection, Database};
use mongodb::bson::doc;
#[cfg(feature = "tasks")]
use mongodb::bson::DateTime;
use tracing::info;
use twilight_model::channel::message::Embed;
use twilight_model::id::Id;
use twilight_model::id::marker::{ChannelMarker, GuildMarker, UserMarker};
Expand Down Expand Up @@ -32,6 +33,7 @@ impl MongoDBConnection {

pub async fn connect(uri: String) -> Result<Self, mongodb::error::Error> {
let client = Client::with_uri_str(uri).await?;
info!("connected to MongoDB");
let db = client.database("custom");
let configs = db.collection::<GuildConfig>("configs");
let cases = db.collection("cases");
Expand All @@ -52,7 +54,6 @@ impl MongoDBConnection {
}

pub async fn get_config(&self, guild_id: Id<GuildMarker>) -> Result<GuildConfig, mongodb::error::Error> {

match self.configs_cache.get(&guild_id){
Some(config) => {
Ok(config.to_owned())
Expand All @@ -62,9 +63,14 @@ impl MongoDBConnection {
doc! {
"guild_id": guild_id.to_string()
}
).await?.unwrap_or_else(|| GuildConfig::new(guild_id));
).await?.unwrap_or_else(|| GuildConfig::new(guild_id.to_owned()));

self.configs_cache.insert(guild_id, config.to_owned());
info!(
name: "cached guild config",
cache_size = self.configs_cache.len(),
%guild_id,
);

Ok(config)
}
Expand Down
9 changes: 7 additions & 2 deletions src/database/redis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::utils::errors::Error;
use redis::AsyncCommands;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::mpsc::error::SendError;
use tracing::info;
use crate::database::mongodb::MongoDBConnection;

#[derive(Serialize, Deserialize, Debug)]
Expand Down Expand Up @@ -127,16 +128,20 @@ impl RedisConnection {
&self,
mongodb: &MongoDBConnection
) -> Result<(), RedisError> {

let mut pubsub = self.client.get_async_pubsub().await?;
pubsub.subscribe("configs").await?;

while let Some(message) = pubsub.on_message().next().await {
const ERROR: &str = "Received invalid payload instead of guild id";
let id: String = message.get_payload().expect(ERROR);
let id: Id<GuildMarker> = Id::from_str(id.as_str()).expect(ERROR);
println!("There is a guild config update id={id}");
mongodb.configs_cache.remove(&id);

info!(
name: "removed config from cache due to update",
cache_size = mongodb.configs_cache.len(),
guild_id = %id,
);
}

Ok(())
Expand Down
9 changes: 6 additions & 3 deletions src/events/automod/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ mod checks;
mod filters;

use std::sync::Arc;
use tracing::info;
use twilight_http::Client;
use twilight_model::channel::Message;
use crate::context::Context;
use crate::events::automod::actions::run_action;
use crate::models::config::automod::TrigerEvent;
use crate::models::config::automod::TriggerEvent;
use crate::models::config::automod::ignore::{Ignore, IgnoreMode};

fn is_ignored(message: &Message, ignore_rule: &Option<Ignore>) -> bool {
Expand Down Expand Up @@ -37,7 +38,7 @@ pub async fn run(
message: Message,
discord_http: Arc<Client>,
context: Arc<Context>,
triger: TrigerEvent
trigger: TriggerEvent
) -> Result<(), ()> {
let guild_id = message.guild_id.ok_or(())?;
let guild_config = Arc::new(context.mongodb.get_config(guild_id).await.map_err(|_| ())?);
Expand All @@ -52,7 +53,7 @@ pub async fn run(
let message = Arc::new(message);

for automod_rule in &automod_config.rules {
if triger == TrigerEvent::MessageUpdate && !automod_rule.check_on_edit { continue }
if trigger == TriggerEvent::MessageUpdate && !automod_rule.check_on_edit { continue }
if is_ignored(&message, &automod_rule.ignore) { continue }

for filter_meta in &automod_rule.filters {
Expand All @@ -64,6 +65,8 @@ pub async fn run(
if !is_allowed { return Ok(()) }
}

info!(name: "automod rule violated", ?message, ?automod_rule, ?trigger);

for action in &automod_rule.actions {
let run = run_action(
action.action.to_owned(),
Expand Down
6 changes: 3 additions & 3 deletions src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use twilight_http::Client;
use twilight_model::gateway::event::Event;
use twilight_model::gateway::payload::incoming::GuildCreate;
use crate::context::Context;
use crate::models::config::automod::TrigerEvent;
use crate::models::config::automod::TriggerEvent;

pub mod automod;
mod case;
Expand All @@ -27,11 +27,11 @@ pub async fn on_event(
}
Event::MessageCreate(event) => {
let message = event.as_ref().0.to_owned();
self::automod::run(message.to_owned(), discord_http, context.to_owned(), TrigerEvent::MessageCreate).await.ok();
self::automod::run(message.to_owned(), discord_http, context.to_owned(), TriggerEvent::MessageCreate).await.ok();
self::top::run(message, context).await.ok();
}
Event::MessageUpdate(event) => {
self::automod::run(event.0, discord_http, context, TrigerEvent::MessageCreate).await.ok();
self::automod::run(event.0, discord_http, context, TriggerEvent::MessageCreate).await.ok();
}
Event::GuildCreate(event) => {
let guild = if let GuildCreate::Available(guild) = *event { guild } else { return Ok(()) };
Expand Down
6 changes: 6 additions & 0 deletions src/events/setup.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::sync::Arc;
use tracing::info;
use twilight_http::Client;
use twilight_model::id::Id;
use twilight_model::id::marker::GuildMarker;
Expand All @@ -16,6 +17,11 @@ pub async fn run(
}
} else { return Ok(()); };

info!(
name: "registering setup command",
%guild_id
);

let application_id = twilight_http.current_user()
.await.map_err(Error::from)?.model().await.map_err(Error::from)?.id;
twilight_http
Expand Down
15 changes: 12 additions & 3 deletions src/gateway/shard.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use std::sync::Arc;
use tracing::error;
use twilight_gateway::{EventTypeFlags, Shard, StreamExt};
use twilight_model::gateway::{Intents, ShardId};
use crate::context::Context;
Expand All @@ -10,7 +11,13 @@ pub async fn connect_shards(
context: Arc<Context>
) {
let token = if let Some(token) = http.token() { token.to_string() }
else { eprintln!("Cannot get token of client {id}"); return };
else {
error!(
name: "cannot get token of client",
client_id = %id
);
return
};

let intents = Intents::MESSAGE_CONTENT | Intents::GUILD_MESSAGES | Intents::GUILDS | Intents::GUILD_MODERATION | Intents::GUILD_MEMBERS;

Expand All @@ -20,8 +27,10 @@ pub async fn connect_shards(
let event = match event {
Ok(event) => event,
Err(err) => {
eprintln!(
"error while receiving events on shard {shard} with {id} client\n{err}",
error!(
name: "error while receiving events",
error = %err,
client_id = %id,
shard = shard.id().number()
);
continue;
Expand Down
5 changes: 5 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::sync::Arc;
use crate::context::Context;
use dotenv::dotenv;
use tokio::task::JoinHandle;
use tracing::info;
use twilight_http::Client;

all_macro!(
Expand All @@ -24,11 +25,15 @@ mod database;
mod models;
pub mod utils;
mod server;
mod tracing_init;

#[tokio::main]
async fn main() {
dotenv().ok();

tracing_init::init();
info!("starting app");

let context = Arc::new(Context::new().await);

let cloned_context = context.clone();
Expand Down
6 changes: 3 additions & 3 deletions src/models/config/automod/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ pub struct AutoModerationRule {
pub name: String,
}

#[derive(PartialEq)]
pub enum TrigerEvent {
#[derive(PartialEq, Debug)]
pub enum TriggerEvent {
MessageCreate,
MessageUpdate
}
}
1 change: 0 additions & 1 deletion src/server/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ impl<T, E: Into<anyhow::Error>> MapErrorIntoInternalRejection<T> for Result<T, E
impl Reject for Rejection {}

pub async fn handle_rejection(rejection: warp::Rejection) -> Result<impl Reply, Infallible> {
println!("{:?}", rejection);
Ok(if let Some(rejection) = rejection.find::<Rejection>() {
warp::reply::with_status(rejection.to_string(), match rejection {
#[cfg(feature = "http-interactions")]
Expand Down
15 changes: 8 additions & 7 deletions src/server/guild/editing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use mongodb::bson::doc;
use mongodb::bson::oid::ObjectId;
use serde_json::{Map, Value};
use tokio::sync::{Mutex, RwLock};
use tracing::{error, warn};
use twilight_model::id::Id;
use twilight_model::id::marker::{GuildMarker, UserMarker};
use crate::context::Context;
Expand Down Expand Up @@ -78,7 +79,7 @@ impl GuildsEditing {
let config = context.mongodb
.get_config(guild_id)
.await
.inspect_err(|error| println!("{error:?}"))
.inspect_err(|error| error!(name: "mongodb error", ?error))
.ok()?;

let guild = self.get_guild(guild_id).await?;
Expand All @@ -100,7 +101,7 @@ impl GuildsEditing {

pub async fn apply_changes(&self, context: &Arc<Context>, guild_id: Id<GuildMarker>) -> Option<()> {
let config = context.mongodb.get_config(guild_id).await
.inspect_err(|error| println!("{error:?}"))
.inspect_err(|error| error!(name: "mongodb error", ?error))
.ok()?;

let is_guild_premium = config.premium;
Expand All @@ -109,20 +110,20 @@ impl GuildsEditing {
let mut guild_lock = guild.lock().await;

let mut new_config = serde_json::to_value(config)
.inspect_err(|error| println!("{error:?}"))
.inspect_err(|error| error!(name: "cannot convert guild config to value", ?error))
.ok()?;
json_patch::merge(&mut new_config, &guild_lock.changes);
let new_config: GuildConfig = serde_json::from_value(new_config)
.inspect_err(|error| println!("{error:?}"))
.inspect_err(|error| error!(name: "cannot marge edits with guild config", ?error))
.ok()?;

if new_config.guild_id != guild_id {
println!("Someone tried changing guild_id in config id={guild_id}");
warn!(name: "someone tried changing guild_id in guild config", %guild_id);
return None
}

if new_config.premium != is_guild_premium {
println!("Someone tried changing premium in config id={guild_id}");
warn!(name: "someone tried changing premium in guild config", %guild_id);
return None
}

Expand All @@ -133,7 +134,7 @@ impl GuildsEditing {
)
.upsert(true)
.await
.inspect_err(|error| println!("{error:?}"))
.inspect_err(|error| error!(name: "mongodb error", ?error))
.ok()?;
context.mongodb.configs_cache.remove(&guild_id);

Expand Down
12 changes: 10 additions & 2 deletions src/server/guild/ws.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::sync::mpsc::UnboundedSender;
use tokio_stream::wrappers::UnboundedReceiverStream;
use tracing::{error, info};
use twilight_model::id::Id;
use twilight_model::id::marker::UserMarker;
use twilight_model::user::CurrentUserGuild;
Expand Down Expand Up @@ -121,7 +122,7 @@ pub async fn handle_connection(
let message = match result {
Ok(message) => message,
Err(error) => {
println!("{error:?}");
error!(name: "error while receiving message on ws_rx channel", ?error);
break
}
};
Expand Down Expand Up @@ -186,10 +187,17 @@ async fn on_message(
let _ = guilds_editing.broadcast_changes(&context, guild.id).await;
}
InboundMessage::ApplyChanges => {
info!(
name: "applying config changes",
author_id = %info.user.id,
guild_id = %guild.id
);
guilds_editing.apply_changes(&context, guild.id).await;
let _ = guilds_editing.broadcast_changes(&context, guild.id).await;
let _ = context.redis.announce_config_update(guild.id).await
.inspect_err(|error| println!("{error}"));
.inspect_err(|error| {
error!(name: "error sending guild_id to redis update announcer", ?error, %guild.id)
});
}
}
}
Loading