|
| 1 | +use crate::extensions::ClientContextExt; |
| 2 | +use anyhow::Result; |
| 3 | +use log::error; |
| 4 | +use serenity::client::Context; |
| 5 | +use serenity::model::interactions::InteractionResponseType; |
| 6 | +use serenity::model::prelude::message_component::ComponentType; |
| 7 | +use serenity::model::prelude::{Interaction, InteractionApplicationCommandCallbackDataFlags}; |
| 8 | + |
| 9 | +pub struct InteractionCreateEvent; |
| 10 | + |
| 11 | +impl InteractionCreateEvent { |
| 12 | + pub async fn run(ctx: &Context, interaction: Interaction) -> Result<()> { |
| 13 | + let db = ctx.get_db().await; |
| 14 | + let mc = interaction.message_component(); |
| 15 | + |
| 16 | + if mc.is_none() { |
| 17 | + return Ok(()); |
| 18 | + } |
| 19 | + |
| 20 | + let component = mc.unwrap(); |
| 21 | + |
| 22 | + if component.data.component_type != ComponentType::Button |
| 23 | + || component.message.embeds.is_empty() |
| 24 | + { |
| 25 | + return Ok(()); |
| 26 | + } |
| 27 | + |
| 28 | + let reminder = |
| 29 | + sqlx::query("SELECT * FROM astra.reminders WHERE user_id = $1 AND launch_id = $2") |
| 30 | + .bind(component.user.id.0 as i64) |
| 31 | + .bind(&component.data.custom_id) |
| 32 | + .fetch_optional(&db.pool) |
| 33 | + .await; |
| 34 | + |
| 35 | + if let Err(e) = reminder { |
| 36 | + error!("Failed to query, {:?}", e); |
| 37 | + return Ok(()); |
| 38 | + } |
| 39 | + |
| 40 | + let reminder_exists = reminder.unwrap().is_some(); |
| 41 | + |
| 42 | + let launch_name = component.message.embeds[0].title.as_ref().unwrap(); |
| 43 | + |
| 44 | + let mut content = if reminder_exists { |
| 45 | + format!("I will stop reminding you for **{}**", launch_name) |
| 46 | + } else { |
| 47 | + format!("I will remind you for **{}**! If you want me to stop from reminding you, hit the button again", launch_name) |
| 48 | + }; |
| 49 | + |
| 50 | + let dm_channel = component.user.create_dm_channel(&ctx).await; |
| 51 | + |
| 52 | + if dm_channel.is_err() { |
| 53 | + content = String::from("Your DM's are closed, please open them and try again."); |
| 54 | + } else { |
| 55 | + let query = if reminder_exists { |
| 56 | + "DELETE FROM astra.reminders WHERE user_id = $1 AND launch_id = $2" |
| 57 | + } else { |
| 58 | + "INSERT INTO astra.reminders (user_id, launch_id) VALUES ($1, $2)" |
| 59 | + }; |
| 60 | + |
| 61 | + sqlx::query(query) |
| 62 | + .bind(component.user.id.0 as i64) |
| 63 | + .bind(&component.data.custom_id) |
| 64 | + .execute(&db.pool) |
| 65 | + .await?; |
| 66 | + } |
| 67 | + |
| 68 | + component |
| 69 | + .create_interaction_response(&ctx, |r| { |
| 70 | + r.kind(InteractionResponseType::ChannelMessageWithSource); |
| 71 | + r.interaction_response_data(|d| { |
| 72 | + d.content(content); |
| 73 | + d.flags(InteractionApplicationCommandCallbackDataFlags::EPHEMERAL) |
| 74 | + }); |
| 75 | + r |
| 76 | + }) |
| 77 | + .await?; |
| 78 | + |
| 79 | + Ok(()) |
| 80 | + } |
| 81 | +} |
0 commit comments