HypeBot/src/discord/tasks.rs

72 lines
2.6 KiB
Rust
Raw Permalink Normal View History

use chrono::{Duration, Utc};
use serenity::prelude::Context;
use crate::discord::{get_db, utility};
use crate::reminder::Reminders;
use crate::INTERESTED_EMOJI;
/// Send reminders
pub async fn send_reminders_task(ctx: &Context) {
let duration = tokio::time::Duration::from_secs(1);
loop {
tokio::time::sleep(duration).await;
let config = utility::get_config(&ctx.data.read().await)
.await
.expect("Unable to get config");
let event_channel_id = config.event_channel;
let reminder_msg: Vec<&String> = match &config.reminders {
None => return,
Some(reminder_msg) => reminder_msg.iter().map(|r| &r.msg).collect(),
};
let db = get_db(&ctx.data.read().await)
.await
.expect("Unable to get DB");
let mut data = ctx.data.write().await;
let reminders = data
.get_mut::<Reminders>()
.expect("Unable to get reminders");
let current_reminders = reminders.get_reminders();
for reminder in current_reminders {
if let Some(event) = db.get_event_by_msg_id(&reminder.event_id) {
let message_id = event.message_id.parse::<u64>().unwrap_or_default();
// Get message id
if let Ok(message) = ctx.http.get_message(event_channel_id, message_id).await {
if let Ok(reaction_users) = message
.reaction_users(ctx, INTERESTED_EMOJI, None, None)
.await
{
// Build reminder message
let msg: String = reminder_msg[reminder.reminder_id]
.replace("{EVENT_NAME}", event.event_name.as_str());
// Send reminder to each reacted user
for user in reaction_users {
utility::send_dm_message(ctx, user, &msg).await;
}
}
}
}
}
}
}
/// Delete old events
pub async fn cleanup_task(ctx: &Context) {
let duration = tokio::time::Duration::from_secs(60 * 60);
loop {
tokio::time::sleep(duration).await;
let db = get_db(&ctx.data.read().await).await.unwrap();
let one_week_ago = Utc::now()
- Duration::from_std(std::time::Duration::from_secs(60 * 60 * 24 * 7)).unwrap();
for event in db.filter_events(|_, event| event.event_time < one_week_ago.naive_utc()) {
utility::delete_event(ctx, &event).await.ok();
}
}
}