Skip to content

Commit

Permalink
added logging
Browse files Browse the repository at this point in the history
  • Loading branch information
ana_rchy committed May 31, 2024
1 parent fd70416 commit 6b1f53d
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 16 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
target/
token.txt
assets/leaderboard.bin
eveningbot.log
33 changes: 33 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ edition = "2021"

[dependencies]
chrono-tz = "0.9.0"
log = "0.4.21"
poise = "0.6.1"
rand = "0.8.5"
reqwest = { version = "0.12.4", features = ["json"] }
rmp-serde = "1.3.0"
serde = "1.0.200"
simplelog = "0.12.2"
time = { version = "0.3.36", features = ["serde", "parsing"] }
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }
tokio-cron-scheduler = "0.10.2"
Expand Down
39 changes: 30 additions & 9 deletions src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::global::*;
use std::sync::atomic::Ordering;
use poise::serenity_prelude::{self as serenity, CreateMessage, EmojiId, GuildRef, ReactionType};
use time::*;
use log::{info, debug};

type Error = Box<dyn std::error::Error + Send + Sync>;

Expand All @@ -20,15 +21,15 @@ pub async fn event_handler(
let guild: GuildRef = ctx.cache.guild(guild_id).unwrap();
guild.member_count
};

let content = format!("<@{}> left, now {} server members",
user.id,
member_count);

let message = CreateMessage::new()
.content(
format!("<@{}> left, now {} server members",
user.id,
member_count)
);

let message = CreateMessage::new().content(&content);
let _ = channel.send_message(&ctx.http, message).await;

info!("{content}");
}

serenity::FullEvent::Message { new_message } => {
Expand Down Expand Up @@ -63,6 +64,8 @@ pub async fn event_handler(

new_message.react(&ctx.http, reaction).await.unwrap();

debug!("GE reaction added for message: {}", new_message.content);


// handle leaderboard if its the first GE of the day
if shared_data.first_ge_sent.load(Ordering::SeqCst) {
Expand All @@ -74,10 +77,26 @@ pub async fn event_handler(
let user_id = u64::from(new_message.author.id);
let mut leaderboard = shared_data.evening_leaderboard.lock().await;

leaderboard.entry(user_id).and_modify(|e| *e += 1).or_insert(1);

let path = format!("{}/assets/leaderboard.bin", shared_data.root_path);
if leaderboard.is_empty() {
debug!("leaderboard hashmap is empty");
} else {
debug!("leaderboard hashmap is filled");
}
if std::path::Path::new(&path).exists() {
debug!("leaderboard file exists");
} else {
debug!("leaderboard file doesnt exist");
}


leaderboard.entry(user_id).and_modify(|e| *e += 1).or_insert(1);

let leaderboard_bytes = rmp_serde::encode::to_vec(&*leaderboard).expect("couldnt serialize leaderboard");
_ = std::fs::write(format!("{}/assets/leaderboard.bin", shared_data.root_path), leaderboard_bytes);
_ = std::fs::write(path, leaderboard_bytes);

info!("first GE of day sent, leaderboard written to");
}

_ => {}
Expand All @@ -98,4 +117,6 @@ async fn easter_egg_reacts(ctx: &serenity::Context, message: &serenity::model::c
};

message.react(&ctx.http, reaction).await.unwrap();

debug!("easter egg reaction added");
}
5 changes: 5 additions & 0 deletions src/global.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use tokio::sync as tsync;
use log::info;


pub struct SharedData {
Expand All @@ -26,8 +27,12 @@ impl SharedData {
let path = std::path::Path::new(&path_string);

if !path.try_exists().expect("file checking error") {
info!("new leaderboard file created");

HashMap::new()
} else {
info!("leaderboard read from file");

let bytes = std::fs::read(format!("{}/assets/leaderboard.bin", assets_path)).expect("couldnt read leaderboard file");
rmp_serde::decode::from_slice(&bytes).expect("couldnt deserialize leaderboard")
}
Expand Down
15 changes: 8 additions & 7 deletions src/jobs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex, atomic::Ordering};
use poise::serenity_prelude::{self as serenity, Colour, CreateEmbed, CreateMessage, Http, UserId};
use tokio_cron_scheduler::{JobBuilder, JobScheduler, JobSchedulerError};
use uuid::Uuid;
use log::debug;

pub async fn init_jobs(
sched: Arc<JobScheduler>,
Expand Down Expand Up @@ -77,6 +78,8 @@ pub async fn init_jobs(
top_10
};

debug!("leaderboard retrieved:\n{leaderboard_top_10}");

let embed = CreateEmbed::new()
.colour(Colour::from_rgb(255, 0, 124))
.title("good evening leaderboard")
Expand Down Expand Up @@ -124,6 +127,9 @@ pub async fn init_jobs(

{ *sunset_time.lock().unwrap() = new_sunset_time; }
{ *sunset_job_id.lock().unwrap() = new_id; }


debug!("sunset job {id} replaced with {new_id}");
})
}))
.build()
Expand Down Expand Up @@ -176,15 +182,10 @@ async fn create_sunset_job(
bag: Arc<Mutex<Vec<&'static str>>>
) -> tokio_cron_scheduler::Job {
let schedule = &format!("{} {} {} * * *", time.second(), time.minute(), time.hour())[..];
println!(
"sunset today - {:02}:{:02}:{:02}",
time.hour(),
time.minute(),
time.second()
);

let channel = serenity::ChannelId::new(channel_id);

debug!("creating new sunset job with schedule {schedule}");

JobBuilder::new()
.with_timezone(chrono_tz::Europe::Dublin)
.with_cron_job_type()
Expand Down
8 changes: 8 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ type Error = Box<dyn std::error::Error + Send + Sync>;

#[tokio::main]
async fn main() -> Result<(), Error> {
let log_config = simplelog::ConfigBuilder::new()
.add_filter_allow_str("eveningbot")
.build();
simplelog::WriteLogger::init(
log::LevelFilter::Debug,
log_config,
std::fs::File::create("eveningbot.log").unwrap())?;

let shared_data = SharedData::new().await;

let mut client = poise_setup(&shared_data).await;
Expand Down
3 changes: 3 additions & 0 deletions src/web.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use serde::Deserialize;
use log::info;

#[derive(Deserialize)]
struct SunriseSunsetIoResponse {
Expand All @@ -23,6 +24,8 @@ pub async fn get_sunset_time() -> Result<time::OffsetDateTime, reqwest::Error> {
.await?
.json::<SunriseSunsetIoResponse>()
.await?;

info!("todays sunset time: {}", resp.results.sunset);

Ok(resp.results.sunset)
}

0 comments on commit 6b1f53d

Please sign in to comment.