Send a reminder when the event starts

This commit is contained in:
2022-10-25 21:11:08 +02:00
parent 8a2e86663d
commit f9c09d61b1

View File

@@ -9,7 +9,7 @@ use std::{env, fs::File, io::BufReader, sync::Arc, time::Duration};
use anyhow::Result;
use async_mutex::Mutex;
use bot::fetch_and_announce_appointment;
use chrono::{NaiveTime, Utc};
use chrono::{DateTime, NaiveTime, TimeZone, Utc};
use chrono_tz::Europe;
use db::ChatInfo;
use diesel::{Connection, RunQueryDsl, SqliteConnection};
@@ -93,6 +93,11 @@ async fn main() {
bot::spawn(bot, db).await;
}
struct Reminder<Tz: TimeZone> {
time: DateTime<Tz>,
text: String,
}
async fn check_task(bot: &Throttle<Bot>, reminder_time: NaiveTime, db: &Database) -> Result<()> {
let chats = db.lock().await.transaction(|db| {
use schema::chat::dsl::*;
@@ -112,40 +117,46 @@ async fn check_task(bot: &Throttle<Bot>, reminder_time: NaiveTime, db: &Database
};
let appointment = appointment.with_timezone(&Europe::Berlin);
if appointment.start < now {
continue;
}
if appointment.start.date_naive() != today {
continue;
}
let reminder_date_time = now.date().and_time(reminder_time).unwrap();
if now < reminder_date_time {
continue;
let mut reminder = None;
if now >= appointment.start {
reminder = Some(Reminder {
time: appointment.start,
text: "Jetzt geht's weiter".into(),
});
} else {
let reminder_date_time = now.date().and_time(reminder_time).unwrap();
if now >= reminder_date_time {
reminder = Some(Reminder {
time: reminder_date_time,
text: format!(
"Heute um {} Uhr geht's weiter",
appointment.start.format("%H:%M")
),
})
}
}
if chat_info.last_reminder.is_some()
&& chat_info.last_reminder.unwrap() >= reminder_date_time
{
continue;
if let Some(reminder) = reminder {
if chat_info.last_reminder.is_some()
&& chat_info.last_reminder.unwrap() >= reminder.time
{
continue;
}
bot.send_message(ChatId(chat_info.id), reminder.text)
.await?;
db.lock().await.transaction(|db| {
use schema::chat::dsl::*;
diesel::update(chat.filter(telegram_id.eq(chat_info.id)))
.set((last_reminder.eq(now.timestamp()),))
.execute(db)
})?;
}
bot.send_message(
ChatId(chat_info.id),
format!(
"Heute um {} Uhr geht's weiter",
appointment.start.format("%H:%M")
),
)
.await?;
db.lock().await.transaction(|db| {
use schema::chat::dsl::*;
diesel::update(chat.filter(telegram_id.eq(chat_info.id)))
.set((last_reminder.eq(now.timestamp()),))
.execute(db)
})?;
}
Ok(())