Skip to content

Commit

Permalink
good evening leaderboard added, + alot of other changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ana-rchy committed May 21, 2024
1 parent 3a2b82a commit 1e303d0
Show file tree
Hide file tree
Showing 8 changed files with 210 additions and 64 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
target/
token.txt
assets/leaderboard.bin
29 changes: 29 additions & 0 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ chrono-tz = "0.9.0"
poise = "0.6.1"
rand = "0.8.5"
reqwest = { version = "0.12.4", features = ["json"] }
rmp-serde = "1.3.0"
serde = "1.0.200"
time = { version = "0.3.36", features = ["serde", "parsing"] }
tokio = { version = "1.37.0", features = ["rt-multi-thread"] }
Expand Down
16 changes: 3 additions & 13 deletions src/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type Context<'a> = poise::Context<'a, SharedData, Error>;

#[poise::command(prefix_command, slash_command)]
pub async fn fact_check(ctx: Context<'_>) -> Result<(), Error> {
let (image, filename) = get_fact_check_image().await;
let (image, filename) = get_fact_check_image(ctx.data()).await;
let attachment = CreateAttachment
::file(&image, filename).await.unwrap();

Expand All @@ -22,8 +22,8 @@ pub async fn fact_check(ctx: Context<'_>) -> Result<(), Error> {
}


async fn get_fact_check_image() -> (File, String) {
let root_folder = get_assets_root_path();
async fn get_fact_check_image(shared_data: &SharedData) -> (File, String) {
let root_folder = &shared_data.root_path;

let paths = std::fs::read_dir(format!("{}/assets/fact_check/", root_folder)).unwrap();
let mut images: Vec<String> = vec![];
Expand All @@ -37,13 +37,3 @@ async fn get_fact_check_image() -> (File, String) {

(File::open(image).await.unwrap(), image.to_string())
}

fn get_assets_root_path() -> String {
let mut exec_path = std::env::current_exe().unwrap();
exec_path.pop();
if cfg!(debug_assertions) {
exec_path.pop(); exec_path.pop();
}

exec_path.to_string_lossy().to_string()
}
35 changes: 29 additions & 6 deletions src/event.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::global::*;
use poise::serenity_prelude::{self as serenity, CreateMessage, GuildRef, ReactionType, EmojiId};
use std::sync::atomic::Ordering;
use poise::serenity_prelude::{self as serenity, CreateMessage, EmojiId, GuildRef, ReactionType};
use time::*;

type Error = Box<dyn std::error::Error + Send + Sync>;
Expand Down Expand Up @@ -31,26 +32,48 @@ pub async fn event_handler(
}

serenity::FullEvent::Message { new_message } => {
// early returns
const BOT_ID: u64 = 1235086289255137404;
#[allow(dead_code)]
const TESTING_CHANNEL_ID: u64 = 1235087573421133824;
const GENERAL_CHANNEL_ID: u64 = 1215048710074011692;

let sunset_time = *shared_data.sunset_time.lock().unwrap();
let current_time = OffsetDateTime::now_utc().to_offset(sunset_time.offset());

if !((current_time > sunset_time && current_time.hour() < 24) || current_time.hour() < 3)
|| new_message.channel_id != GENERAL_CHANNEL_ID
if !(current_time > sunset_time && current_time.hour() < 24)
|| !(new_message.channel_id == GENERAL_CHANNEL_ID || new_message.channel_id == TESTING_CHANNEL_ID)
|| new_message.author.id == BOT_ID
|| !GOOD_EVENINGS.contains(&&new_message.content.to_lowercase()[..])
{
return Ok(());
}


// react to good evenings
let reaction = ReactionType::Custom {
animated: false,
id: EmojiId::new(1241916769648775238),
name: Some("eepy".to_string()),
};

if GOOD_EVENINGS.contains(&&new_message.content.to_lowercase()[..]) {
new_message.react(&ctx.http, reaction).await.unwrap();
new_message.react(&ctx.http, reaction).await.unwrap();


// handle leaderboard if its the first GE of the day
if shared_data.first_ge_sent.load(Ordering::SeqCst) {
return Ok(());
}

shared_data.first_ge_sent.store(true, Ordering::SeqCst);

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 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);
}

_ => {}
Expand Down
40 changes: 39 additions & 1 deletion src/global.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,45 @@
use crate::web;
use std::collections::HashMap;
use std::sync::atomic::AtomicBool;
use std::sync::{Arc, Mutex};
use tokio::sync as tsync;


pub struct SharedData {
pub sunset_time: Arc<Mutex<time::OffsetDateTime>>
pub sunset_time: Arc<Mutex<time::OffsetDateTime>>,
pub root_path: String,
pub evening_leaderboard: Arc<tsync::Mutex<HashMap<u64, u16>>>,
pub first_ge_sent: Arc<AtomicBool>
}

impl SharedData {
pub async fn new() -> Self {
let mut exec_path = std::env::current_exe().expect("couldnt get current executable path");
exec_path.pop();
if cfg!(debug_assertions) {
exec_path.pop(); exec_path.pop();
}
let assets_path = exec_path.to_string_lossy().to_string();

let leaderboard: HashMap<u64, u16> = {
let path_string = format!("{}/assets/leaderboard.bin", assets_path);
let path = std::path::Path::new(&path_string);

if !path.try_exists().expect("file checking error") {
HashMap::new()
} else {
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")
}
};

SharedData {
sunset_time: Arc::new(Mutex::new(web::get_sunset_time().await.unwrap())),
root_path: assets_path,
evening_leaderboard: Arc::new(tsync::Mutex::new(leaderboard)),
first_ge_sent: Arc::new(AtomicBool::new(false))
}
}
}

pub static EVENING_MOTD: &[&str] = &[
Expand Down
Loading

0 comments on commit 1e303d0

Please sign in to comment.