Compare commits

...

11 commits

Author SHA1 Message Date
Ladislav Hano
bef22f9609 v0.3 2024-02-18 12:30:02 +01:00
Ladislav Hano
8949409947 basic gifs implementation 2024-02-18 12:14:02 +01:00
Ladislav Hano
4be8cd231f Deleted embeds.rs 2024-02-17 18:50:06 +01:00
Ladislav Hano
f1b37f1725 Created Tenor struct for Tenor api calls 2024-02-17 18:49:13 +01:00
Ladislav Hano
6792f8192b Loď 2024-02-16 22:49:57 +01:00
Ladislav Hano
fc3685e471 Version number change 2024-02-16 22:34:49 +01:00
Ladislav Hano
ea1afa270c Version number for debug 2024-02-16 22:31:12 +01:00
Ladislav Hano
4a7ac0c023 Ready for new release 2024-02-16 22:06:12 +01:00
ZyLacx
1186cd3226
Merge pull request #4 from ZyLacx/notices
Created cron job for events and birthdays announcements
2024-02-16 21:55:27 +01:00
Ladislav Hano
bbc34312bb Created cron job for events and birthdays announcements 2024-02-16 21:54:07 +01:00
ZyLacx
843acc4675
Merge pull request #3 from ZyLacx/sqlx
Sqlx addition, simple queries for events and birthdays
2024-02-15 20:34:09 +01:00
14 changed files with 619 additions and 99 deletions

2
.gitignore vendored
View file

@ -10,4 +10,4 @@
# IDE config # IDE config
.vscode .vscode
mooverdb.db mooverdb.db*

219
Cargo.lock generated
View file

@ -286,6 +286,17 @@ dependencies = [
"cfg-if", "cfg-if",
] ]
[[package]]
name = "cron"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1ff76b51e4c068c52bfd2866e1567bee7c567ae8f24ada09fd4307019e25eab7"
dependencies = [
"chrono",
"nom",
"once_cell",
]
[[package]] [[package]]
name = "crossbeam-queue" name = "crossbeam-queue"
version = "0.3.11" version = "0.3.11"
@ -466,6 +477,21 @@ version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]] [[package]]
name = "form_urlencoded" name = "form_urlencoded"
version = "1.2.1" version = "1.2.1"
@ -768,6 +794,19 @@ dependencies = [
"tokio-rustls 0.24.1", "tokio-rustls 0.24.1",
] ]
[[package]]
name = "hyper-tls"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905"
dependencies = [
"bytes",
"hyper",
"native-tls",
"tokio",
"tokio-native-tls",
]
[[package]] [[package]]
name = "iana-time-zone" name = "iana-time-zone"
version = "0.1.59" version = "0.1.59"
@ -841,6 +880,12 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "json"
version = "0.12.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd"
[[package]] [[package]]
name = "lazy_static" name = "lazy_static"
version = "1.4.0" version = "1.4.0"
@ -955,18 +1000,39 @@ dependencies = [
[[package]] [[package]]
name = "moover_rust" name = "moover_rust"
version = "0.1.0" version = "0.3.0"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
"dotenv", "dotenv",
"form_urlencoded",
"json",
"rand", "rand",
"regex", "regex",
"reqwest",
"serenity 0.12.0", "serenity 0.12.0",
"serenity_utils", "serenity_utils",
"sqlx", "sqlx",
"tokio", "tokio",
"tokio_schedule", "tokio-cron-scheduler",
]
[[package]]
name = "native-tls"
version = "0.2.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07226173c32f2926027b63cce4bcd8076c3552846cbe7925f3aaffeac0a3b92e"
dependencies = [
"lazy_static",
"libc",
"log",
"openssl",
"openssl-probe",
"openssl-sys",
"schannel",
"security-framework",
"security-framework-sys",
"tempfile",
] ]
[[package]] [[package]]
@ -1007,6 +1073,17 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "num-derive"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d"
dependencies = [
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]] [[package]]
name = "num-integer" name = "num-integer"
version = "0.1.46" version = "0.1.46"
@ -1062,6 +1139,50 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "openssl"
version = "0.10.63"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15c9d69dd87a29568d4d017cfe8ec518706046a05184e5aea92d0af890b803c8"
dependencies = [
"bitflags 2.4.2",
"cfg-if",
"foreign-types",
"libc",
"once_cell",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.48",
]
[[package]]
name = "openssl-probe"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
version = "0.9.99"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22e1bf214306098e4832460f797824c05d25aacdf896f64a985fb0fd992454ae"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "ordered-float" name = "ordered-float"
version = "2.10.1" version = "2.10.1"
@ -1254,9 +1375,9 @@ checksum = "c08c74e62047bb2de4ff487b251e4a92e24f48745648451635cec7d591162d9f"
[[package]] [[package]]
name = "reqwest" name = "reqwest"
version = "0.11.23" version = "0.11.24"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b1ae8d9ac08420c66222fb9096fc5de435c3c48542bc5336c51892cffafb41" checksum = "c6920094eb85afde5e4a138be3f2de8bbdf28000f0029e72c45025a56b042251"
dependencies = [ dependencies = [
"base64 0.21.7", "base64 0.21.7",
"bytes", "bytes",
@ -1268,11 +1389,13 @@ dependencies = [
"http-body", "http-body",
"hyper", "hyper",
"hyper-rustls", "hyper-rustls",
"hyper-tls",
"ipnet", "ipnet",
"js-sys", "js-sys",
"log", "log",
"mime", "mime",
"mime_guess", "mime_guess",
"native-tls",
"once_cell", "once_cell",
"percent-encoding", "percent-encoding",
"pin-project-lite", "pin-project-lite",
@ -1281,8 +1404,10 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"serde_urlencoded", "serde_urlencoded",
"sync_wrapper",
"system-configuration", "system-configuration",
"tokio", "tokio",
"tokio-native-tls",
"tokio-rustls 0.24.1", "tokio-rustls 0.24.1",
"tokio-util", "tokio-util",
"tower-service", "tower-service",
@ -1418,6 +1543,15 @@ version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c" checksum = "f98d2aa92eebf49b69786be48e4477826b256916e84a57ff2a4f21923b48eb4c"
[[package]]
name = "schannel"
version = "0.1.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fbc91545643bcf3a0bbb6569265615222618bdf33ce4ffbbd13c4bbd4c093534"
dependencies = [
"windows-sys 0.52.0",
]
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.2.0"
@ -1444,6 +1578,29 @@ dependencies = [
"zeroize", "zeroize",
] ]
[[package]]
name = "security-framework"
version = "2.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de"
dependencies = [
"bitflags 1.3.2",
"core-foundation",
"core-foundation-sys",
"libc",
"security-framework-sys",
]
[[package]]
name = "security-framework-sys"
version = "2.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a"
dependencies = [
"core-foundation-sys",
"libc",
]
[[package]] [[package]]
name = "serde" name = "serde"
version = "1.0.195" version = "1.0.195"
@ -1907,6 +2064,12 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "sync_wrapper"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2047c6ded9c721764247e62cd3b03c09ffc529b2ba5b10ec482ae507a4a70160"
[[package]] [[package]]
name = "system-configuration" name = "system-configuration"
version = "0.5.1" version = "0.5.1"
@ -2021,6 +2184,21 @@ dependencies = [
"windows-sys 0.48.0", "windows-sys 0.48.0",
] ]
[[package]]
name = "tokio-cron-scheduler"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d1215c91d6f74868e18a65bda99853e012cfb2a0e42f3438382e318277da76a0"
dependencies = [
"chrono",
"cron",
"num-derive",
"num-traits",
"tokio",
"tracing",
"uuid",
]
[[package]] [[package]]
name = "tokio-macros" name = "tokio-macros"
version = "2.2.0" version = "2.2.0"
@ -2032,6 +2210,16 @@ dependencies = [
"syn 2.0.48", "syn 2.0.48",
] ]
[[package]]
name = "tokio-native-tls"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
dependencies = [
"native-tls",
"tokio",
]
[[package]] [[package]]
name = "tokio-rustls" name = "tokio-rustls"
version = "0.23.4" version = "0.23.4"
@ -2093,16 +2281,6 @@ dependencies = [
"tracing", "tracing",
] ]
[[package]]
name = "tokio_schedule"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b4a14ab1658c39d137ebcc5fbaab364c9922a6cc04ab48b364546c2e6022256"
dependencies = [
"chrono",
"tokio",
]
[[package]] [[package]]
name = "tower-service" name = "tower-service"
version = "0.3.2" version = "0.3.2"
@ -2284,6 +2462,15 @@ version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f00cc9702ca12d3c81455259621e676d0f7251cec66a21e98fe2e9a37db93b2a"
dependencies = [
"getrandom",
]
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"
version = "0.2.15" version = "0.2.15"
@ -2379,9 +2566,9 @@ checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b"
[[package]] [[package]]
name = "wasm-streams" name = "wasm-streams"
version = "0.3.0" version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4609d447824375f43e1ffbc051b50ad8f4b3ae8219680c94452ea05eb240ac7" checksum = "b65dc4c90b63b118468cf747d8bf3566c1913ef60be765b5730ead9e0a3ba129"
dependencies = [ dependencies = [
"futures-util", "futures-util",
"js-sys", "js-sys",

View file

@ -1,6 +1,6 @@
[package] [package]
name = "moover_rust" name = "moover_rust"
version = "0.1.0" version = "0.3.0"
edition = "2021" edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
@ -8,8 +8,7 @@ edition = "2021"
[dependencies] [dependencies]
rand = "0.8.5" rand = "0.8.5"
anyhow = "1.0.71" anyhow = "1.0.71"
# tokio-cron-scheduler = "0.9.4" tokio-cron-scheduler = "0.10.0"
tokio_schedule = "0.3.1"
dotenv = "0.15.0" dotenv = "0.15.0"
# poise = "0.5.5" # poise = "0.5.5"
serenity = { version = "0.12.0", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "http", "cache"] } serenity = { version = "0.12.0", default-features = false, features = ["client", "gateway", "rustls_backend", "model", "http", "cache"] }
@ -18,6 +17,9 @@ tokio = { version = "1.29.1", features = ["macros", "rt-multi-thread"] }
regex = "1.9.0" regex = "1.9.0"
chrono = "0.4.31" chrono = "0.4.31"
sqlx = {version="0.7.3", features=["runtime-tokio", "sqlite"]} sqlx = {version="0.7.3", features=["runtime-tokio", "sqlite"]}
json = "0.12.4"
reqwest = "0.11.24"
form_urlencoded = "1.2.1"
[features] [features]
DEBUG = [] DEBUG = []

View file

@ -1,24 +1,21 @@
use std::sync::atomic::AtomicUsize;
use chrono::Utc;
use serenity::async_trait; use serenity::async_trait;
use serenity::model::channel::Message; use serenity::prelude::GatewayIntents;
use serenity::model::gateway::Ready;
use serenity::prelude::*;
use serenity::client::Context; use serenity::client::Context;
use serenity::model::gateway::Ready;
use serenity::all::{Message, EventHandler};
use serenity::Client;
// use tokio_cron_scheduler::{JobScheduler, JobToRun, Job}; use tokio_cron_scheduler::{JobScheduler, Job};
use tokio_schedule::{every, EveryDay, Job};
use util::security::dotenv_var; use util::security::dotenv_var;
use std::sync::Arc;
mod message_handler; mod message_handler;
use message_handler::handle; use message_handler::handle;
use std::future::Future;
use std::pin::Pin;
mod commands; mod commands;
mod util; mod util;
use util::debug::send_error;
mod other; mod other;
use other::notice; use other::notice;
@ -32,34 +29,24 @@ impl EventHandler for Handler {
} }
async fn ready(&self, ctx: Context, ready: Ready) { async fn ready(&self, ctx: Context, ready: Ready) {
println!("{} is connected!", ready.user.name); println!("{} v0.3 is connected!", ready.user.name);
#[cfg(feature="RELEASE")] { #[cfg(feature="RELEASE")] {
use util::debug::hello; use util::debug::hello;
hello(ctx.http.clone()).await; hello(ctx.http.clone()).await;
} }
// notice::notice_wrapper(ctx).await; let sched = JobScheduler::new().await.unwrap();
// let scheduler = every(1).day().at(13, 30, 0) let job_closure = move |_, _| -> Pin<Box<dyn Future<Output = ()> + Send>> {
// .perform(|| async { let ctx_clone = ctx.clone();
// notice::notice_wrapper(ctx.clone()).await Box::pin( async move {
// }).await; notice::notice_wrapper(ctx_clone).await;
})
};
// let mut scheduler = JobScheduler::new().await; sched.add(Job::new_async("0 0 13 * * *", job_closure).expect("Cron job not set up correctly")).await.unwrap();
// scheduler. sched.start().await.unwrap();
// scheduler.add(match Job::new_async("5 * * * * * *", |uuid, mut l| Box::pin( async {
// notice::notice(ctx.clone()).await;
// })) {
// Ok(_) => {}
// Err(e) => {
// send_error(ctx.http.clone(), e.to_string());
// panic!()
// }
// });
// scheduler.add(Job::new(daily("22"), move || {
// notice::notice(ctx.clone())
// }));
} }
} }

View file

@ -1,4 +1,5 @@
use rand::random; use rand::random;
use serenity::http::CacheHttp;
use serenity::{client::Context, http::Http}; use serenity::{client::Context, http::Http};
use serenity::model::channel::Message; use serenity::model::channel::Message;
use std::sync::Arc; use std::sync::Arc;
@ -28,12 +29,19 @@ pub async fn handle(ctx: Context, msg: Message) {
} }
} }
if random::<u16>() % 1000 == 666 {
match msg.reply(ctx.http(), "Povedz loď").await {
Ok(_) => {},
Err(e) => send_error(ctx.http.clone(), e.to_string()).await
}
}
let channel_id = match moove_check(&msg).await { let channel_id = match moove_check(&msg).await {
Some(val) => val, Some(val) => val,
None => return None => return
}; };
match moove(ctx.http, msg, channel_id).await { match moove(ctx.http, msg.clone(), channel_id).await {
Ok(_) => return, Ok(_) => return,
Err(e) => println!("ERROR: {e}") Err(e) => println!("ERROR: {e}")
}; };

View file

View file

@ -1 +1,4 @@
pub mod notice; pub mod notice;
pub mod tenor_builder;
pub mod tenor_types;
pub mod tenor;

View file

@ -1,18 +1,22 @@
use chrono::{Datelike, Local}; use chrono::{Datelike, Local};
use serenity::{all::{GuildId, UserId}, http::Http, prelude::*};
use serenity::{all::{GuildId, UserId}, builder::{CreateEmbed, CreateMessage}, client::Context, http::Http, model::Colour};
// use anyhow::Ok;
use sqlx::{Connection, FromRow, SqliteConnection};
use crate::util::security::dotenv_var;
use crate::util::debug::send_error; use crate::util::debug::send_error;
use crate::util::utilities;
use anyhow::Ok;
use std::sync::Arc; use std::sync::Arc;
use crate::util::security::dotenv_var; use super::{tenor, tenor_builder::Tenor, tenor_types::{ContentFilter, MediaFilter}};
use sqlx::{FromRow, Connection, SqliteConnection};
// pub async fn notice_wrapper(http: Arc<Http>) {
pub async fn notice_wrapper(ctx: Context) { pub async fn notice_wrapper(ctx: Context) {
match notice(ctx.clone()).await { match notice(ctx.http.clone()).await {
Err(e) => { Err(e) => {
send_error(ctx.http.clone(), e.to_string()).await; send_error(ctx.http.clone(), e.to_string()).await;
return; return;
@ -21,88 +25,146 @@ pub async fn notice_wrapper(ctx: Context) {
} }
} }
async fn announce_event(guild_id: GuildId, name: &str, special_message: &str, http: Arc<Http>) { async fn announce_event(guild_id: GuildId, name: &str, special_message: &str, http: Arc<Http>) -> anyhow::Result<()> {
let mut event_embed = CreateEmbed::new()
.color(Colour::new(rand::random::<u32>() % 0xFFFFFF))
.title("Today's event is:");
let system_channel = utilities::get_system_channel(guild_id, http.clone()).await?;
if special_message.contains("http") {
event_embed = event_embed.description(name);
system_channel.send_message(http.clone(),
CreateMessage::new().add_embed(event_embed.clone()).content(special_message)).await?;
// Ok(());
}
event_embed = event_embed.field(name, special_message, true);
system_channel.send_message(http.clone(),
CreateMessage::new().add_embed(event_embed)).await?;
Ok(())
} }
async fn celebrate_birthday(guild_id: GuildId, user_id: UserId, nick: &str, http: Arc<Http>) { async fn celebrate_birthday(guild_id: GuildId, user_id: UserId, nick: &str, http: Arc<Http>) -> anyhow::Result<()> {
const LIMIT: u8 = 20;
let tenor_response = Tenor::new()
.random(true)
.contentfilter(ContentFilter::low)
.add_media_filter(MediaFilter::gif)
.search("vsetko najlepsie").await?;
let index = rand::random::<usize>() % LIMIT as usize;
let gif_url = match tenor::get_gif_url(MediaFilter::gif, tenor_response) {
Ok(urls) => Some(urls),
Err(e) => {
send_error(http.clone(), e.to_string()).await;
None
}
};
let system_channel = utilities::get_system_channel(guild_id, http.clone()).await?;
let mut embed = CreateEmbed::new()
.color(Colour::new(rand::random::<u32>() % 0xFFFFFF))
.title(format!("HAPPY BIRTHDAY {}!", nick))
.description(format!("<@{}>'s birthday is today!!! Yay!", user_id.get()));
if gif_url.is_some() {
embed = embed.image(gif_url.unwrap()[index].as_str());
}
system_channel.send_message(http.clone(), CreateMessage::new().add_embed(embed.clone())).await?;
Ok(())
} }
#[derive(Clone, FromRow, Debug)] #[derive(Clone, FromRow, Debug)]
struct BirthdayRow { struct BirthdayRow {
#[sqlx(try_from="i64")] #[sqlx(try_from="i64")]
id: u64, id: u64,
day: u8,
month: u8,
nick: String, nick: String,
} }
#[derive(Clone, FromRow, Debug)] #[derive(Clone, FromRow, Debug)]
struct EventRow { struct EventRow {
id: u32,
#[sqlx(try_from="i64")] #[sqlx(try_from="i64")]
guild: u64, guild: u64,
name: String, name: String,
day: u8, year: i32,
month: u8,
special_message: String, special_message: String,
} }
async fn notice(ctx: serenity::client::Context) -> anyhow::Result<()> { async fn notice(http: Arc<Http>) -> anyhow::Result<()> {
use anyhow::Context; use anyhow::Context;
let local = Local::now(); let local = Local::now();
let day = local.day(); let day = local.day();
let month = local.month(); let month = local.month();
let year = local.year();
let db_path = dotenv_var("DATABASE_URL").context("DATABASE_URL not found in env")?; let db_path = dotenv_var("DATABASE_URL").context("DATABASE_URL not found in env")?;
let mut db = SqliteConnection::connect(db_path.as_str()).await?; let mut db = SqliteConnection::connect(db_path.as_str()).await?;
let birtdays = sqlx::query_as::<_, BirthdayRow>( let birtdays = sqlx::query_as::<_, BirthdayRow>(
"SELECT * FROM birthdays "SELECT id, nick FROM birthdays
WHERE day=? AND month=?;" WHERE day=? AND month=?;"
) )
.bind(day) .bind(day)
.bind(month) .bind(month)
.fetch_all(&mut db) .fetch_all(&mut db)
.await?; .await?;
let global_events = sqlx::query_as::<_, EventRow>( let global_events = sqlx::query_as::<_, EventRow>(
"SELECT guild, name, day, month, specialMessage from events "SELECT id, guild, name, year, special_message from events
WHERE day=? AND month=? AND guild=0;" WHERE day=? AND month=? AND guild=0;"
) )
.bind(day) .bind(day)
.bind(month) .bind(month)
.fetch_all(&mut db) .fetch_all(&mut db)
.await?; .await?;
let guilds = ctx.http.get_guilds(None, None).await?; let guilds = http.get_guilds(None, None).await?;
for guild in guilds { for guild in guilds {
let guild_id = guild.id; let guild_id = guild.id;
for bd in &birtdays { for bd in &birtdays {
let user_id = UserId::new(bd.id); let user_id = UserId::new(bd.id);
guild_id.member(ctx.http(), user_id).await?; guild_id.member(http.clone(), user_id).await?;
celebrate_birthday(guild_id, user_id, bd.nick.as_str(), ctx.http.clone()).await; celebrate_birthday(guild_id, user_id, bd.nick.as_str(), http.clone()).await?;
} }
// TODO if has year delete it from announce and delete
for e in &global_events { for e in &global_events {
announce_event(guild_id, e.name.as_str(), e.special_message.as_str(), ctx.http.clone()).await; if e.year != 0 && e.year != year {
continue;
}
announce_event(guild_id, e.name.as_str(), e.special_message.as_str(), http.clone()).await?;
} }
} }
let global_events = sqlx::query_as::<_, EventRow>( let guild_events = sqlx::query_as::<_, EventRow>(
"SELECT guild, name, day, month, specialMessage from events "SELECT id, guild, name, year, special_message from events
WHERE day=? AND month=? AND guild!=0;" WHERE day=? AND month=? AND guild!=0;"
) )
.bind(day) .bind(day)
.bind(month) .bind(month)
.fetch_all(&mut db) .fetch_all(&mut db)
.await?; .await?;
for e in &global_events { // TODO if has year delete it from announce and delete
announce_event(GuildId::new(e.guild), e.name.as_str(), e.special_message.as_str(), ctx.http.clone()).await;
for e in &guild_events {
announce_event(GuildId::new(e.guild), e.name.as_str(), e.special_message.as_str(), http.clone()).await?;
} }
Ok(()) Ok(())

View file

@ -0,0 +1,17 @@
use super::tenor_types::MediaFilter;
use json::JsonValue;
pub fn get_gif_url(filter: MediaFilter, tenor_response: JsonValue) -> anyhow::Result<Vec<String>> {
use anyhow::Context;
let mut urls: Vec<String> = Vec::new();
let results = tenor_response["results"].members();
for result in results {
let url = result["media_formats"][filter.to_string()]["url"].as_str().context("Value not found in Json")?;
urls.push(url.to_string());
}
Ok(urls)
}

171
src/other/tenor_builder.rs Normal file
View file

@ -0,0 +1,171 @@
use json::JsonValue;
use std::collections::HashSet;
use anyhow::Error;
use crate::util::security::dotenv_var;
use super::tenor_types::{ContentFilter, ArRange, MediaFilter};
pub struct Tenor {
/// Specify the country of origin for the request. To do so, provide its two-letter ISO 3166-1 country code.
country: Option<String>,
/// Specify the default language to interpret the search string using ISO 639-1 language code + optional two-letter ISO 3166-1 country code.
/// You can use the country code that you provide in locale to differentiate between dialects of the given language.
locale: Option<String>,
/// Specify the content safety filter level
/// The default value is off
contentfilter: Option<ContentFilter>,
/// Set of GIF formats to filter
/// By default returns all formats
media_filter: Option<HashSet<MediaFilter>>,
/// Filter to only include GIFS with the aspect ratios that fit within range
/// Default value is all
/// wide: 0.42 <= aspect ratio <= 2.36
/// standard: 0.56 <= aspect ratio <= 1.78
ar_range: Option<ArRange>,
/// Whether to randomly order the response
/// Default value is false
random: Option<bool>,
/// Fetch up to the specified number of results
/// Default value (for Tenor) is 20 and maximum is 50
/// if smaller or greater values is provided, the value is clamped to the min/max
limit: Option<u8>,
/// Retrieve results that start at the position
/// Use a non-zero, non-empty value from next, returned by the API response, to get the next set of results
pos: Option<String>
}
impl Tenor {
pub fn new() -> Self {
Tenor {
country: None,
locale: None,
contentfilter: None,
media_filter: None,
ar_range: None,
random: None,
limit: None,
pos: None
}
}
/// Replaces current country with the passed one
pub fn country(mut self, country: String) -> Self {
self.country = Some(country);
self
}
/// Replaces current locale with the passed one
pub fn locale(mut self, locale: String) -> Self {
self.locale = Some(locale);
self
}
/// Replaces current media_filter with the passed one
pub fn media_filter(mut self, filter: HashSet<MediaFilter>) -> Self {
self.media_filter = Some(filter);
self
}
/// Replaces current contentfilter with the passed one
pub fn contentfilter(mut self, filter: ContentFilter) -> Self {
self.contentfilter = Some(filter);
self
}
/// Replaces current media_filter with the passed one
pub fn add_media_filter(mut self, filter: MediaFilter) -> Self {
if self.media_filter.is_none() {
let mut set = HashSet::new();
set.insert(filter);
self.media_filter = Some(set);
}
else {
self.media_filter.as_mut().unwrap().insert(filter);
}
self
}
pub fn ar_range(mut self, range: ArRange) -> Self {
self.ar_range = Some(range);
self
}
pub fn random(mut self, random: bool) -> Self {
self.random = Some(random);
self
}
pub fn limit(mut self, mut limit: u8) -> Self {
if limit < 20 {
limit = 20;
}
else if limit > 50 {
limit = 50;
}
self.limit = Some(limit);
self
}
pub fn pos(mut self, pos: String) -> Self {
self.pos = Some(pos);
self
}
pub async fn search(self, query: &str) -> Result<JsonValue, Error> {
use anyhow::Context;
let q: String = form_urlencoded::byte_serialize(query.as_bytes()).collect();
let base_url = "https://tenor.googleapis.com/v2/search?";
let api_key = dotenv_var("TENORV2").context("TENORV2 key not found in the .env")?;
let mut request = format!("{base_url}q={q}&key={api_key}");
if self.country.is_some() {
request.push_str(&format!("&country={}", self.country.unwrap()));
}
if self.locale.is_some() {
request.push_str(&format!("&locale={}", self.locale.unwrap()));
}
if self.contentfilter.is_some() {
request.push_str(&format!("&contentfilter={}", self.contentfilter.unwrap()))
}
if self.media_filter.is_some() && self.media_filter.as_ref().unwrap().len() > 0 {
request.push_str(
format!("&media_filter={}",
self.media_filter.unwrap()
.iter()
.map(|e| e.to_string())
.collect::<Vec<_>>()
.join(",")
.as_str()
).as_str()
);
}
if self.ar_range.is_some() {
request.push_str(&format!("&ar_range={}", self.ar_range.unwrap()));
}
if self.random.is_some() {
request.push_str(&format!("&random={}", self.random.unwrap()));
}
if self.limit.is_some() {
request.push_str(&format!("&limit={}", self.limit.unwrap()));
}
let response = reqwest::get(request).await?.text().await?;
let response_json = json::parse(&response)?;
Ok(response_json)
}
}

63
src/other/tenor_types.rs Normal file
View file

@ -0,0 +1,63 @@
#![allow(non_camel_case_types)]
use std::fmt;
#[derive(Debug)]
pub enum ContentFilter {
off,
low,
medium,
high
}
impl fmt::Display for ContentFilter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
/// More information here https://developers.google.com/tenor/guides/response-objects-and-errors#media-object
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum MediaFilter {
preview,
gif,
mediumgif,
tinygif,
nanogif,
mp4,
loopedmp4,
tinymp4,
nanomp4,
webm,
tinywebm,
nanowebm,
webp_transparent,
tinywebp_transparent,
nanowebp_transparent,
gif_transparent,
tinygif_transparent,
nanogif_transparent
}
impl fmt::Display for MediaFilter {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Debug)]
pub enum ArRange {
all,
wide,
standard
}
impl fmt::Display for ArRange {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}

View file

@ -1,18 +1,27 @@
use serenity::{all::ChannelId, builder::CreateMessage, http::Http}; use std::sync::Arc;
use std::{process::exit, sync::Arc};
pub async fn send_error(http: Arc<Http>, msg: String) { use serenity::http::Http;
pub async fn send_error(_http: Arc<Http>, msg: String) {
println!("ERROR: {msg}"); println!("ERROR: {msg}");
#[cfg(feature="RELEASE")] #[cfg(feature="RELEASE")] {
match ChannelId::new(1199495008416440491) use serenity::all::ChannelId;
.send_message(http, CreateMessage::new().content(msg)).await { use serenity::all::CreateMessage;
Ok(_) => { return; } use std::process::exit;
Err(_) => { exit(-1) }
match ChannelId::new(1199495008416440491)
.send_message(_http, CreateMessage::new().content(msg)).await {
Ok(_) => { return; }
Err(_) => { exit(-1) }
}; };
}
} }
#[cfg(feature="RELEASE")]
pub async fn hello(http: Arc<Http>) { pub async fn hello(http: Arc<Http>) {
use serenity::all::ChannelId;
let messages = [ let messages = [
"AAAAAAAAAAAAAAAAAAAA", "AAAAAAAAAAAAAAAAAAAA",
"Henlooo", "Henlooo",

View file

@ -1,2 +1,3 @@
pub mod security; pub mod security;
pub mod debug; pub mod debug;
pub mod utilities;

View file

@ -0,0 +1,10 @@
use std::sync::Arc;
use serenity::{all::{GuildId, ChannelId}, http::Http};
use anyhow::Context;
pub async fn get_system_channel(guild_id: GuildId, http: Arc<Http>) -> anyhow::Result<ChannelId> {
return http.get_guild(guild_id).await?.system_channel_id
.context(format!("System channel of guild: {} not found", guild_id.get()));
}