diff options
| author | Cara Salter <cara@devcara.com> | 2022-04-14 13:06:54 -0400 | 
|---|---|---|
| committer | Cara Salter <cara@devcara.com> | 2022-04-18 23:05:25 -0400 | 
| commit | ffacf1c8fc820de3890ba6231b644e9e4a65ce28 (patch) | |
| tree | 475537cef44f8eb0e7ed1269fd8c76e700c62918 /src | |
| parent | 9b4707192557cdd64dd82c5883e54758d0d66512 (diff) | |
| download | glitch-ng-ffacf1c8fc820de3890ba6231b644e9e4a65ce28.tar.gz glitch-ng-ffacf1c8fc820de3890ba6231b644e9e4a65ce28.zip | |
FLAKE
Diffstat (limited to 'src')
| -rw-r--r-- | src/commands/actions.rs | 2 | ||||
| -rw-r--r-- | src/commands/osu.rs | 3 | ||||
| -rw-r--r-- | src/handler.rs | 10 | ||||
| -rw-r--r-- | src/main.rs | 26 | ||||
| -rw-r--r-- | src/models.rs | 10 | 
5 files changed, 50 insertions, 1 deletions
| diff --git a/src/commands/actions.rs b/src/commands/actions.rs index 63d00fb..a283238 100644 --- a/src/commands/actions.rs +++ b/src/commands/actions.rs @@ -114,6 +114,8 @@ pub async fn hug(      Ok(())  } + +/// Takes in a specific vector of URLs and returns a random one  fn get_random_url_from_vec(vec: Vec<&str>) -> &str {      let mut url = "";      let rand = rand::thread_rng().gen_range(0..vec.len()); diff --git a/src/commands/osu.rs b/src/commands/osu.rs index 8d91f56..5e0b563 100644 --- a/src/commands/osu.rs +++ b/src/commands/osu.rs @@ -18,6 +18,9 @@ struct OsuTokenRequest {      pub scope: String,  } +/// This is kinda loose, and we should really be caching the osu token +/// +/// Eh well, this *works* (sort of)  async fn setup_reqwest() -> Result<reqwest::Client, Error> {      let client_id = std::env::var("OSU_CLIENT_ID").unwrap();      let client_secret = std::env::var("OSU_CLIENT_SECRET").unwrap(); diff --git a/src/handler.rs b/src/handler.rs index ef8fc00..7b4568f 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -3,6 +3,12 @@ use poise::serenity_prelude as serenity;  use crate::models::ReactionRole;  use crate::{Data, Error}; +use tracing::info; + +/** + * Handles specific events, including ReactionAdd, which is needed for the reaction role handler to + * function properly + */  pub async fn event_handler(      ctx: &serenity::Context,      event: &poise::Event<'_>, @@ -16,6 +22,7 @@ pub async fn event_handler(                  if add_reaction.user_id.unwrap() == current_user.id {                      return Ok(());                  } +                // This fetches the role and lets us query extra data including role ID                  let rrole = sqlx::query_as!(                      ReactionRole,                      "SELECT * FROM reaction_roles WHERE message_id=$1 AND reaction=$2", @@ -31,6 +38,7 @@ pub async fn event_handler(                          add_reaction.user_id.unwrap().0,                      )                      .await?; +                // Honestly, not really needed.                  let member_roles = member.roles;                  let role_id = serenity::RoleId(rrole.role_id.parse::<u64>()?);                  if member_roles.contains(&role_id) { @@ -60,7 +68,7 @@ pub async fn event_handler(                      .await {                          dm_chan.say(ctx, format!("Toggled the role!")).await?;                      } else { -                        println!("Could not DM user, but we did the role anyways"); +                        info!("Could not DM user, but we did the role anyways");                      }                  add_reaction.delete(&ctx.http).await?; diff --git a/src/main.rs b/src/main.rs index 8693381..88d612e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,10 @@ +#![forbid(missing_docs)] +/*! + * Full rewrite of the [Glitch](https://glitchbot.net) bot in Poise with slash commands + * + * This iteration will focus on code correctness and durability. The major goal is to avoid what + * happened to the Campmaster by avoiding code rot and forcing documentation on _everything_ + */  use std::{sync::Mutex, time::Duration};  use dotenv::dotenv; @@ -11,6 +18,7 @@ mod commands;  mod handler;  mod models; +/// Contains data shared between all commands  pub struct Data {      pg: Mutex<PgPool>,  } @@ -60,6 +68,7 @@ async fn register(ctx: Context<'_>, #[flag] global: bool) -> Result<(), Error> {  #[tokio::main]  #[instrument]  async fn main() { +    // Initialize environment and logging      dotenv().unwrap();      tracing_subscriber::fmt::init();      info!("Initialized logging"); @@ -86,7 +95,9 @@ async fn main() {                  ..commands::reactionroles::rroles()              },          ], +        // This requires a closure, for some reason          on_error: |error| Box::pin(on_error(error)), +        // Honestly could probably be removed, but it's kept in for ~reasons~          pre_command: |ctx| {              Box::pin(async move {                  println!("Executing command {}...", ctx.command().name); @@ -101,12 +112,15 @@ async fn main() {          prefix_options: poise::PrefixFrameworkOptions {              prefix: Some("~".into()),              edit_tracker: Some(poise::EditTracker::for_timespan(Duration::from_secs(3600))), +            // These don't work, I thought they might but -\_()_/-              additional_prefixes: vec![                  poise::Prefix::Literal("hey glitch"),                  poise::Prefix::Literal("hey glitch,"),              ],              ..Default::default()          }, +        // For once, we abstracted the handler *out* of main.rs so we can actually read the damn +        // file          listener: |ctx, event, _, data| Box::pin(handler::event_handler(ctx, event, data)),          ..Default::default()      }; @@ -115,6 +129,18 @@ async fn main() {          .token(std::env::var("DISCORD_TOKEN").unwrap_or("BAD-TOKEN".into()))          .user_data_setup(move |_ctx, _ready, _framework| {              Box::pin(async move { +                /* +                 * Hoo boy okay +                 * +                 * This sets up the postgres pool and adds it to the Data struct we defined +                 * earlier. Once that's done, it runs the migrations that have been embeded within +                 * the completed binary +                 * +                 * A sane default was chosen if DATABASE_URL doesn't exist +                 * +                 * If migrations fail, we panic and exit because then we're in an incorrect DB +                 * state and something needs to be fixed before any further work can be done. +                 */                  let pool = PgPoolOptions::new()                      .max_connections(5)                      .connect( diff --git a/src/models.rs b/src/models.rs index 431204a..09d5d7c 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,9 +1,19 @@ +/** + * Describes a Reaction Role as it appears in SQL + */  #[derive(Debug, Clone)]  pub struct ReactionRole { +    /// The primary key      pub id: i32, +    /// The ID of the channel where the menu is kept, turned into a String for ease of storage      pub channel_id: String, +    /// The ID of the message within the channel containing the reaction menu      pub message_id: String, +    /// The ID of the guild containing the channel      pub guild_id: String, +    /// The String representation of the reaction, either as a unicode Emoji or a discord custom +    /// emoji ID      pub reaction: String, +    /// The ID of the role to be toggled by the menu option      pub role_id: String,  } | 
