feat: basic setup for link slash command

This commit is contained in:
silver 2023-09-17 15:25:17 +01:00
parent 591c61b009
commit 14cbf0bcad
6 changed files with 238 additions and 41 deletions

1
Cargo.lock generated
View file

@ -2422,6 +2422,7 @@ dependencies = [
"dotenvy", "dotenvy",
"lettre", "lettre",
"maud", "maud",
"rand 0.8.5",
"serde", "serde",
"serenity", "serenity",
"sqlx", "sqlx",

View file

@ -24,6 +24,9 @@ dotenvy = "0.15.7"
# For sqlite # For sqlite
sqlx = { version = "0.7.1", features = [ "runtime-tokio", "sqlite" ] } sqlx = { version = "0.7.1", features = [ "runtime-tokio", "sqlite" ] }
# create random strings
rand = "0.8.5"
# fancy time stuff # fancy time stuff
chrono = "0.4.26" chrono = "0.4.26"

View file

@ -43,6 +43,7 @@ impl From<&RecordCSV> for Wolves {
Self { Self {
id_wolves: input.mem_id.to_owned(), id_wolves: input.mem_id.to_owned(),
email: input.email.to_owned(), email: input.email.to_owned(),
verified: false,
discord: None, discord: None,
minecraft: None, minecraft: None,
} }
@ -77,9 +78,11 @@ fn get_csv(config: &Config) -> Result<Vec<Csv>, Box<dyn std::error::Error>> {
continue; continue;
} }
let mut tmp = ServerMembers::from(&record);
tmp.server = config.skynet_server;
result.push(Csv { result.push(Csv {
wolves: Wolves::from(&record), wolves: Wolves::from(&record),
server_members: ServerMembers::from(&record), server_members: tmp,
}); });
} }
} }

View file

@ -1,20 +1,38 @@
use serenity::builder::CreateApplicationCommand; use lettre::{
use serenity::client::Context; message::{header, MultiPart, SinglePart},
use serenity::model::application::interaction::application_command::ApplicationCommandInteraction; transport::smtp::{self, authentication::Credentials},
use serenity::model::id::GuildId; Message, SmtpTransport, Transport,
use serenity::model::prelude::command::CommandOptionType; };
use serenity::model::prelude::interaction::application_command::CommandDataOptionValue; use maud::html;
use skynet_discord_bot::{get_now_iso, DataBase, Wolves}; use serenity::{
builder::CreateApplicationCommand,
client::Context,
model::{
application::interaction::application_command::ApplicationCommandInteraction,
prelude::{command::CommandOptionType, interaction::application_command::CommandDataOptionValue},
},
};
use skynet_discord_bot::{get_now_iso, random_string, Config, DataBase, Wolves, WolvesVerify};
use sqlx::{Pool, Sqlite}; use sqlx::{Pool, Sqlite};
pub async fn run(options: &ApplicationCommandInteraction, ctx: &Context) -> String { pub async fn run(command: &ApplicationCommandInteraction, ctx: &Context) -> String {
let db_lock = { let db_lock = {
let data_read = ctx.data.read().await; let data_read = ctx.data.read().await;
data_read.get::<DataBase>().expect("Expected Config in TypeMap.").clone() data_read.get::<DataBase>().expect("Expected Databse in TypeMap.").clone()
}; };
let db = db_lock.read().await; let db = db_lock.read().await;
let option = options let config_lock = {
let data_read = ctx.data.read().await;
data_read.get::<Config>().expect("Expected Config in TypeMap.").clone()
};
let config = config_lock.read().await;
if get_server_member_discord(&db, &command.user.name).await.is_some() {
return "Already linked".to_string();
}
let option = command
.data .data
.options .options
.get(0) .get(0)
@ -23,11 +41,44 @@ pub async fn run(options: &ApplicationCommandInteraction, ctx: &Context) -> Stri
.as_ref() .as_ref()
.expect("Expected email object"); .expect("Expected email object");
if let CommandDataOptionValue::String(email) = option { let email = if let CommandDataOptionValue::String(email) = option {
format!("Email is {}, user is {} {:?}", email, options.user.name, options.guild_id) email
} else { } else {
"Please provide a valid user".to_string() return "Please provide a valid user".to_string();
};
// check if email exists
let details = match get_server_member_email(&db, email).await {
None => return "Please check is the same as on https://ulwolves.ie/".to_string(),
Some(x) => x,
};
if details.verified {
return "Email already verified".to_string();
} }
db_pending_clear_expired(&db).await;
// send mail
if get_from_db(&db, &command.user.name).await.is_some() {
return "Please check email".to_string();
}
// generate a auth key
let auth = random_string(20);
match send_mail(&config, &details, &auth, &command.user.name) {
Ok(_) => match save_to_db(&db, &details, &auth, &command.user.name).await {
Ok(_) => {}
Err(e) => {
return format!("Unable to save to db {} {e:?}", &details.email);
}
},
Err(e) => {
return format!("Unable to send mail to {} {e:?}", &details.email);
}
}
format!("Verification email sent to {}, user is {} {:?}", email, command.user.name, command.guild_id)
} }
pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand { pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicationCommand {
@ -37,22 +88,143 @@ pub fn register(command: &mut CreateApplicationCommand) -> &mut CreateApplicatio
.create_option(|option| option.name("email").description("UL Wolves Email").kind(CommandOptionType::String).required(true)) .create_option(|option| option.name("email").description("UL Wolves Email").kind(CommandOptionType::String).required(true))
} }
async fn get_server_member_bulk(db: &Pool<Sqlite>, server: &GuildId) -> Vec<Wolves> { async fn get_server_member_discord(db: &Pool<Sqlite>, user: &str) -> Option<Wolves> {
sqlx::query_as::<_, Wolves>( sqlx::query_as::<_, Wolves>(
r#" r#"
SELECT * SELECT *
FROM server_members FROM wolves
JOIN wolves ON server_members.id_wolves = wolves.id_wolves WHERE discord =
WHERE (
server = ?
AND discord IS NOT NULL
AND expiry > ?
)
"#, "#,
) )
.bind(*server.as_u64() as i64) .bind(user)
.bind(get_now_iso(true)) .fetch_one(db)
.fetch_all(db) .await
.ok()
}
async fn get_server_member_email(db: &Pool<Sqlite>, email: &str) -> Option<Wolves> {
sqlx::query_as::<_, Wolves>(
r#"
SELECT *
FROM wolves
WHERE email = ?
"#,
)
.bind(email)
.fetch_one(db)
.await
.ok()
}
fn send_mail(config: &Config, email: &Wolves, auth: &str, user: &str) -> Result<smtp::response::Response, smtp::Error> {
let mail = &email.email;
let discord = "https://discord.skynet.ie";
let sender = format!("UL Computer Society <{}>", &config.mail_user);
// Create the html we want to send.
let html = html! {
head {
title { "Hello from Skynet!" }
style type="text/css" {
"h2, h4 { font-family: Arial, Helvetica, sans-serif; }"
}
}
div style="display: flex; flex-direction: column; align-items: center;" {
h2 { "Hello from Skynet!" }
// Substitute in the name of our recipient.
p { "Hi " (user) "," }
p {
"Please use " pre { "/verify " (auth)} " to verify your discord account."
}
p {
"If you have issues please refer to our Discord server:"
br;
a href=(discord) { (discord) }
}
p {
"Skynet Team"
br;
"UL Computer Society"
}
}
};
let body_text = format!(
r#"
Hi {user}
Please use "/verify {auth}" to verify your discord account.
If you have issues please refer to our Discord server:
{discord}
Skynet Team
UL Computer Society
"#
);
// Build the message.
let email = Message::builder()
.from(sender.parse().unwrap())
.to(mail.parse().unwrap())
.subject("Skynet-Discord: Link Wolves.")
.multipart(
// This is composed of two parts.
// also helps not trip spam settings (uneven number of url's
MultiPart::alternative()
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_PLAIN).body(body_text))
.singlepart(SinglePart::builder().header(header::ContentType::TEXT_HTML).body(html.into_string())),
)
.expect("failed to build email");
let creds = Credentials::new(config.mail_user.clone(), config.mail_pass.clone());
// Open a remote connection to gmail using STARTTLS
let mailer = SmtpTransport::starttls_relay(&config.mail_smtp).unwrap().credentials(creds).build();
// Send the email
mailer.send(&email)
}
async fn db_pending_clear_expired(pool: &Pool<Sqlite>) -> Option<WolvesVerify> {
sqlx::query_as::<_, WolvesVerify>(
r#"
DELETE
FROM wolves_verify
WHERE date_expiry < ?
"#,
)
.bind(get_now_iso(true))
.fetch_one(pool)
.await
.ok()
}
async fn get_from_db(db: &Pool<Sqlite>, user: &str) -> Option<WolvesVerify> {
sqlx::query_as::<_, WolvesVerify>(
r#"
SELECT *
FROM wolves_verify
WHERE discord =
"#,
)
.bind(user)
.fetch_one(db)
.await
.ok()
}
async fn save_to_db(db: &Pool<Sqlite>, record: &Wolves, auth: &str, user: &str) -> Result<Option<WolvesVerify>, sqlx::Error> {
sqlx::query_as::<_, WolvesVerify>(
"
INSERT INTO wolves_verify (email, discord, auth_code, date_expiry)
VALUES (?1, ?2, ?3, ?4)
",
)
.bind(record.email.to_owned())
.bind(user)
.bind(auth.to_owned())
.bind(get_now_iso(false))
.fetch_optional(db)
.await .await
.unwrap_or_default()
} }

View file

@ -9,6 +9,7 @@ use serenity::{
}; };
use chrono::{Datelike, SecondsFormat, Utc}; use chrono::{Datelike, SecondsFormat, Utc};
use rand::{distributions::Alphanumeric, thread_rng, Rng};
use sqlx::{ use sqlx::{
sqlite::{SqliteConnectOptions, SqlitePoolOptions, SqliteRow}, sqlite::{SqliteConnectOptions, SqlitePoolOptions, SqliteRow},
Error, FromRow, Pool, Row, Sqlite, Error, FromRow, Pool, Row, Sqlite,
@ -127,23 +128,21 @@ impl<'r> FromRow<'r, SqliteRow> for ServerMembers {
} }
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]
pub struct Wolves { pub struct Wolves {
pub id_wolves: String, pub id_wolves: String,
pub email: String, pub email: String,
pub verified: bool,
pub discord: Option<String>, pub discord: Option<String>,
pub minecraft: Option<String>, pub minecraft: Option<String>,
} }
impl<'r> FromRow<'r, SqliteRow> for Wolves { #[derive(Debug, Clone, Deserialize, Serialize, sqlx::FromRow)]
fn from_row(row: &'r SqliteRow) -> Result<Self, Error> { pub struct WolvesVerify {
Ok(Self { pub email: String,
id_wolves: row.try_get("id_wolves")?, pub discord: String,
email: row.try_get("email")?, pub auth_code: String,
discord: row.try_get("discord")?, pub date_expiry: String,
minecraft: row.try_get("minecraft")?,
})
}
} }
#[derive(Debug, Clone, Deserialize, Serialize)] #[derive(Debug, Clone, Deserialize, Serialize)]
@ -202,7 +201,8 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
id_wolves text PRIMARY KEY, id_wolves text PRIMARY KEY,
email text not null, email text not null,
discord text, discord text,
minecraft text minecraft text,
verified integer DEFAULT FALSE
)", )",
) )
.execute(&pool) .execute(&pool)
@ -210,6 +210,21 @@ pub async fn db_init(config: &Config) -> Result<Pool<Sqlite>, Error> {
sqlx::query("CREATE INDEX IF NOT EXISTS index_discord ON wolves (discord)").execute(&pool).await?; sqlx::query("CREATE INDEX IF NOT EXISTS index_discord ON wolves (discord)").execute(&pool).await?;
sqlx::query(
"CREATE TABLE IF NOT EXISTS wolves_verify (
email text PRIMARY KEY,
discord text not null,
auth_code text not null,
date_expiry text not null
)",
)
.execute(&pool)
.await?;
sqlx::query("CREATE INDEX IF NOT EXISTS index_date_expiry ON wolves_verify (date_expiry)")
.execute(&pool)
.await?;
sqlx::query( sqlx::query(
"CREATE TABLE IF NOT EXISTS server_members ( "CREATE TABLE IF NOT EXISTS server_members (
server integer not null, server integer not null,
@ -304,3 +319,7 @@ pub fn get_now_iso(short: bool) -> String {
now.to_rfc3339_opts(SecondsFormat::Millis, true) now.to_rfc3339_opts(SecondsFormat::Millis, true)
} }
} }
pub fn random_string(len: usize) -> String {
thread_rng().sample_iter(&Alphanumeric).take(len).map(char::from).collect()
}

View file

@ -67,6 +67,7 @@ impl EventHandler for Handler {
async fn interaction_create(&self, ctx: Context, interaction: Interaction) { async fn interaction_create(&self, ctx: Context, interaction: Interaction) {
if let Interaction::ApplicationCommand(command) = interaction { if let Interaction::ApplicationCommand(command) = interaction {
let _ = command.defer_ephemeral(&ctx.http).await;
//println!("Received command interaction: {:#?}", command); //println!("Received command interaction: {:#?}", command);
let content = match command.data.name.as_str() { let content = match command.data.name.as_str() {
@ -75,10 +76,8 @@ impl EventHandler for Handler {
}; };
if let Err(why) = command if let Err(why) = command
.create_interaction_response(&ctx.http, |response| { .edit_original_interaction_response(&ctx.http, |response| {
response response.content(content)
.kind(InteractionResponseType::ChannelMessageWithSource)
.interaction_response_data(|message| message.content(content).ephemeral(true))
}) })
.await .await
{ {