From 202e3e2e1ae2dd16ed4ebf4169834e4b9dd24458 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Djk=C3=A1=C5=A5o?= Date: Wed, 14 Feb 2024 13:44:29 +0100 Subject: [PATCH 1/3] sqlx --- .env | 1 + .gitignore | 4 ++-- Cargo.toml | 6 ++---- src/other/notice.rs | 31 ++++++++++++++++--------------- 4 files changed, 21 insertions(+), 21 deletions(-) create mode 100644 .env diff --git a/.env b/.env new file mode 100644 index 0000000..01ec508 --- /dev/null +++ b/.env @@ -0,0 +1 @@ +DATABASE_URL="" diff --git a/.gitignore b/.gitignore index dad345c..e9a20e7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,10 +2,10 @@ /target # Tokens -.env +# .env # Hidden files /src/.* # IDE config -.vscode \ No newline at end of file +.vscode diff --git a/Cargo.toml b/Cargo.toml index df96261..e4eb15a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,11 +16,9 @@ serenity = { version = "0.12.0", default-features = false, features = ["client", serenity_utils = "0.7.0" tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] } regex = "1.9.0" -# sqlite = "0.32.0" -# async-sqlite = { version = "0.2.1", default-features = false } -async-rusqlite = "0.4.0" chrono = "0.4.31" +sqlx = {version="0.7.3", features=["runtime-tokio", "sqlite"]} [features] DEBUG = [] -RELEASE = [] \ No newline at end of file +RELEASE = [] diff --git a/src/other/notice.rs b/src/other/notice.rs index 5b3b0c6..27f5028 100644 --- a/src/other/notice.rs +++ b/src/other/notice.rs @@ -1,20 +1,16 @@ +use chrono::{Datelike, Local}; use serenity::prelude::*; -use chrono::{Local, Datelike}; - -// use async_sqlite::{rusqlite::{Rows, Statement}, ClientBuilder, JournalMode}; use crate::util::debug::send_error; use anyhow::Result; -use async_rusqlite::Connection; - pub async fn notice_wrapper(ctx: Context) { match notice(ctx.clone()).await { Ok(_) => return, Err(e) => { send_error(ctx.http.clone(), e.to_string()).await; - return + return; } } } @@ -22,7 +18,7 @@ pub async fn notice_wrapper(ctx: Context) { struct BirtdayRow { day: u8, month: u8, - nick: String + nick: String, } async fn notice(ctx: Context) -> anyhow::Result<()> { @@ -30,12 +26,16 @@ async fn notice(ctx: Context) -> anyhow::Result<()> { let day = local.day(); let month = local.month(); + let pool = sqlx::sqlite::SqlitePoolOptions::new() + .connect("my.db") + .await?; - let conn = Connection::open("my.db").await?; - - let stmt = conn.call(move |conn| { - conn.prepare("SELECT * FROM birthdays WHERE day=6 AND month=3;") - }).await?; + let birtdays: Vec = sqlx::query_as!( + BirtdayRow, + "SELECT * FROM birthdays WHERE day=6 AND month=3;" + ) + .fetch(&pool) + .await?; // let result = Vec::new(); // let stmt = client.conn(|conn| { @@ -50,18 +50,19 @@ async fn notice(ctx: Context) -> anyhow::Result<()> { let bd = BirtdayRow { day: row.get(1)?, month: row.get(2)?, - nick: row.get(3)? + nick: row.get(3)?, }; result.push(bd); } println!("VALUE: {:?}", result[0].day); // for db in ["birthdays", "events"] { - + // // let mut stmt = client.conn(|conn| { // // conn. // // }).await; // } Ok(()) -} \ No newline at end of file +} + From 015b00aa07e3bafa120a03c0cb5bbcb6560170e1 Mon Sep 17 00:00:00 2001 From: Ladislav Hano <524934@mail.muni.cz> Date: Thu, 15 Feb 2024 20:27:52 +0100 Subject: [PATCH 2/3] Added sqlx to connect to sqlite database --- .gitignore | 4 +- src/main.rs | 13 ++--- src/message_handler.rs | 2 +- src/other/embeds.rs | 0 src/other/notice.rs | 108 ++++++++++++++++++++++++++++------------- src/other/tenor.rs | 0 6 files changed, 86 insertions(+), 41 deletions(-) create mode 100644 src/other/embeds.rs create mode 100644 src/other/tenor.rs diff --git a/.gitignore b/.gitignore index e9a20e7..9857dba 100644 --- a/.gitignore +++ b/.gitignore @@ -2,10 +2,12 @@ /target # Tokens -# .env +.env # Hidden files /src/.* # IDE config .vscode + +mooverdb.db \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 3871408..adf8600 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,11 +34,12 @@ impl EventHandler for Handler { async fn ready(&self, ctx: Context, ready: Ready) { println!("{} is connected!", ready.user.name); + #[cfg(feature="RELEASE")] { + use util::debug::hello; + hello(ctx.http.clone()).await; + } - // use util::debug::hello; - // hello(ctx.http.clone()).await; - - notice::notice_wrapper(ctx).await; + // notice::notice_wrapper(ctx).await; // let scheduler = every(1).day().at(13, 30, 0) // .perform(|| async { @@ -65,13 +66,13 @@ impl EventHandler for Handler { #[tokio::main] async fn main() -> anyhow::Result<()> { use anyhow::Context; - + let token_str = "TOKEN"; #[cfg(feature="DEBUG")] let token_str = "DEBUGTOKEN"; - let token = dotenv_var(token_str).context("No TOKEN in env")?; + let token = dotenv_var(token_str).context("TOKEN not found in env")?; let intents = GatewayIntents::GUILD_MESSAGES | GatewayIntents::MESSAGE_CONTENT; diff --git a/src/message_handler.rs b/src/message_handler.rs index 43d561f..d55a4a6 100644 --- a/src/message_handler.rs +++ b/src/message_handler.rs @@ -44,7 +44,7 @@ async fn response(http: Arc, msg: Message) -> bool { const RESPONSES: [&str; 4] = [ "To som jaaa", "Henloooo", - "Čo môj?", + "No čo je?", "Hm?" ]; diff --git a/src/other/embeds.rs b/src/other/embeds.rs new file mode 100644 index 0000000..e69de29 diff --git a/src/other/notice.rs b/src/other/notice.rs index 27f5028..b2d1ea2 100644 --- a/src/other/notice.rs +++ b/src/other/notice.rs @@ -1,67 +1,109 @@ use chrono::{Datelike, Local}; -use serenity::prelude::*; +use serenity::{all::{GuildId, UserId}, http::Http, prelude::*}; use crate::util::debug::send_error; -use anyhow::Result; +use anyhow::Ok; + +use std::sync::Arc; + +use crate::util::security::dotenv_var; + +use sqlx::{FromRow, Connection, SqliteConnection}; pub async fn notice_wrapper(ctx: Context) { match notice(ctx.clone()).await { - Ok(_) => return, Err(e) => { send_error(ctx.http.clone(), e.to_string()).await; return; - } + }, + Result::Ok(_) => return } } -struct BirtdayRow { +async fn announce_event(guild_id: GuildId, name: &str, special_message: &str, http: Arc) { +} + +async fn celebrate_birthday(guild_id: GuildId, user_id: UserId, nick: &str, http: Arc) { +} + +#[derive(Clone, FromRow, Debug)] +struct BirthdayRow { + #[sqlx(try_from="i64")] + id: u64, day: u8, month: u8, nick: String, } -async fn notice(ctx: Context) -> anyhow::Result<()> { +#[derive(Clone, FromRow, Debug)] +struct EventRow { + #[sqlx(try_from="i64")] + guild: u64, + name: String, + day: u8, + month: u8, + special_message: String, +} + +async fn notice(ctx: serenity::client::Context) -> anyhow::Result<()> { + use anyhow::Context; + let local = Local::now(); let day = local.day(); let month = local.month(); - let pool = sqlx::sqlite::SqlitePoolOptions::new() - .connect("my.db") - .await?; + let db_path = dotenv_var("DATABASE_URL").context("DATABASE_URL not found in env")?; - let birtdays: Vec = sqlx::query_as!( - BirtdayRow, - "SELECT * FROM birthdays WHERE day=6 AND month=3;" + let mut db = SqliteConnection::connect(db_path.as_str()).await?; + + let birtdays = sqlx::query_as::<_, BirthdayRow>( + "SELECT * FROM birthdays + WHERE day=? AND month=?;" ) - .fetch(&pool) + .bind(day) + .bind(month) + .fetch_all(&mut db) .await?; - // let result = Vec::new(); - // let stmt = client.conn(|conn| { - // // conn.prepare(format!("SELECT * FROM {db} WHERE day={day} AND month={month};").as_str()); - // conn.prepare("SELECT * FROM birthdays WHERE day=6 AND month=3;") - // }).await?; + let global_events = sqlx::query_as::<_, EventRow>( + "SELECT guild, name, day, month, specialMessage from events + WHERE day=? AND month=? AND guild=0;" + ) + .bind(day) + .bind(month) + .fetch_all(&mut db) + .await?; - let rows = stmt.query([])?; + let guilds = ctx.http.get_guilds(None, None).await?; - let result: Vec = Vec::new(); - while let Some(row) = rows.next()? { - let bd = BirtdayRow { - day: row.get(1)?, - month: row.get(2)?, - nick: row.get(3)?, - }; - result.push(bd); + for guild in guilds { + let guild_id = guild.id; + + for bd in &birtdays { + let user_id = UserId::new(bd.id); + guild_id.member(ctx.http(), user_id).await?; + + celebrate_birthday(guild_id, user_id, bd.nick.as_str(), ctx.http.clone()).await; + } + + for e in &global_events { + announce_event(guild_id, e.name.as_str(), e.special_message.as_str(), ctx.http.clone()).await; + } } - println!("VALUE: {:?}", result[0].day); - // for db in ["birthdays", "events"] { + let global_events = sqlx::query_as::<_, EventRow>( + "SELECT guild, name, day, month, specialMessage from events + WHERE day=? AND month=? AND guild!=0;" + ) + .bind(day) + .bind(month) + .fetch_all(&mut db) + .await?; - // // let mut stmt = client.conn(|conn| { - // // conn. - // // }).await; - // } + for e in &global_events { + announce_event(GuildId::new(e.guild), e.name.as_str(), e.special_message.as_str(), ctx.http.clone()).await; + } Ok(()) } diff --git a/src/other/tenor.rs b/src/other/tenor.rs new file mode 100644 index 0000000..e69de29 From e8d74ab1134898d4149c17535974b1920a27e4b0 Mon Sep 17 00:00:00 2001 From: Ladislav Hano <524934@mail.muni.cz> Date: Thu, 15 Feb 2024 20:32:31 +0100 Subject: [PATCH 3/3] Delete .env --- .env | 1 - 1 file changed, 1 deletion(-) delete mode 100644 .env diff --git a/.env b/.env deleted file mode 100644 index 01ec508..0000000 --- a/.env +++ /dev/null @@ -1 +0,0 @@ -DATABASE_URL=""