diff options
| author | Cara Salter <cara@devcara.com> | 2022-01-19 20:14:50 -0500 | 
|---|---|---|
| committer | Cara Salter <cara@devcara.com> | 2022-01-19 20:14:50 -0500 | 
| commit | 943196546dc3f9b5cc4356cebb8468775a127471 (patch) | |
| tree | 35d826e3271bd7aece9aa394cd44542bb7f69a9f /src | |
| parent | 7d868aedd1147c484d82ea4815c5c53af834eacb (diff) | |
| download | glitch-ng-943196546dc3f9b5cc4356cebb8468775a127471.tar.gz glitch-ng-943196546dc3f9b5cc4356cebb8468775a127471.zip  | |
pony: Add ponybyid
Required adding the derpi ID to the footer of all the other pony embeds
TODO: Refactor generating the pony embeds out of the commands
Signed-off-by: Cara Salter <cara@devcara.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/commands/pony.rs | 71 | ||||
| -rw-r--r-- | src/main.rs | 14 | 
2 files changed, 74 insertions, 11 deletions
diff --git a/src/commands/pony.rs b/src/commands/pony.rs index b908ca4..532937a 100644 --- a/src/commands/pony.rs +++ b/src/commands/pony.rs @@ -9,6 +9,7 @@ pub struct PonyResponse {      pub pony: Pony,  } +#[allow(non_snake_case)]  #[derive(Deserialize)]  pub struct Pony {      pub id: u64, @@ -24,6 +25,7 @@ pub struct Pony {      pub representations: PonyRepresentation,  } +#[allow(non_snake_case)]  #[derive(Deserialize)]  pub struct PonyRepresentation {      pub full: String, @@ -39,11 +41,10 @@ pub struct PonyRepresentation {  /// Retrieves a random SFW pony image  #[poise::command(slash_command, prefix_command)]  pub async fn randpony(ctx: Context<'_>) -> Result<(), Error> { -    let mut response_msg = ctx +    let response_msg = ctx          .say("Fetching a random pony image, please wait!")          .await?; -    let client = reqwest::Client::new();      let res = reqwest::get("https://theponyapi.com/api/v1/pony/random")          .await?          .json::<PonyResponse>() @@ -64,13 +65,12 @@ pub async fn randpony(ctx: Context<'_>) -> Result<(), Error> {                      } else {                          e.field("Source", "None found", true);                      } -                    e -                }); -                m +                    e.footer(|f| f.text(format!("Pony ID: {}", res.pony.id))) +                })              })              .await?;          } -        Err(e) => { +        Err(_) => {              ctx.say("Error editing message").await?;          }      }; @@ -91,7 +91,7 @@ pub async fn tpony(      #[rest]      tags: String,  ) -> Result<(), Error> { -    let mut response_msg = ctx +    let response_msg = ctx          .say(format!(              "Fetching pony image based on tags: {:?}",              tags.clone() @@ -119,9 +119,8 @@ pub async fn tpony(                      } else {                          e.field("Source", "None found", true);                      } -                    e -                }); -                m +                    e.footer(|f| f.text(format!("Pony ID: {}", res.pony.id))) +                })              })              .await?;          } @@ -133,6 +132,58 @@ pub async fn tpony(      Ok(())  } +/// Gets a specific pony based on the ID +/// +/// Usage: +///   /ponybyid <id> +#[poise::command(slash_command, prefix_command)] +pub async fn ponybyid( +    ctx: Context<'_>, +    #[description = "The ID to search for"] id: String, +) -> Result<(), Error> { +    let response_msg = ctx +        .say(format!("Fetching pony based on id: {}", id)) +        .await?; + +    let res = match reqwest::get(format!("https://theponyapi.com/api/v1/pony/id/{}", id).as_str()) +        .await +    { +        Ok(r) => r.json::<PonyResponse>().await?, +        Err(_) => { +            response_msg.unwrap().message().await.unwrap().edit(ctx.discord(), |m| { +                m.content("There was an error fetching that pony, please double-check your ID and try again.") +            }).await?; +            return Ok(()); +        } +    }; + +    match response_msg.unwrap().message().await { +        Ok(mut msg) => { +            msg.edit(&ctx.discord(), |m| { +                m.content(""); +                m.embed(|e| { +                    e.title("Pony!"); +                    e.image(res.pony.representations.full.clone()); +                    let res_tags = get_tags_as_string(res.pony.tags); +                    e.field("Tags", format!("{:?}", res_tags), true); +                    if let Some(url) = res.pony.sourceURL { +                        e.field("Source", url, true); +                    } else { +                        e.field("Source", "None found", true); +                    } +                    e.footer(|f| f.text(format!("Pony ID: {}", res.pony.id))) +                }) +            }) +            .await? +        } +        Err(e) => { +            ctx.say("Could not edit message").await?; +        } +    }; + +    Ok(()) +} +  fn get_tags_as_string(tags: Vec<String>) -> String {      let mut response = String::from(tags.get(0).unwrap());      for (i, s) in tags.iter().enumerate() { diff --git a/src/main.rs b/src/main.rs index bfd39c7..2968f20 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ use std::{sync::Mutex, time::Duration};  use dotenv::dotenv;  use sqlx::{postgres::PgPoolOptions, PgPool}; +use tracing::{info, instrument};  type Error = Box<dyn std::error::Error + Send + Sync>;  type Context<'a> = poise::Context<'a, Data, Error>; @@ -34,6 +35,9 @@ async fn on_error(error: poise::FrameworkError<'_, Data, Error>) {          poise::FrameworkError::Setup { error } => panic!("Failed to start bot: {:?}", error),          poise::FrameworkError::Command { error, ctx } => {              println!("Error in command {}: {:?}", ctx.command().name, error); +            ctx.say(format!("Whoops! Something went wrong: {:?}", error)) +                .await +                .unwrap();          }          error => {              if let Err(e) = poise::builtins::on_error(error).await { @@ -54,8 +58,11 @@ async fn register(ctx: Context<'_>, #[flag] global: bool) -> Result<(), Error> {  }  #[tokio::main] +#[instrument]  async fn main() {      dotenv().unwrap(); +    tracing_subscriber::fmt::init(); +    info!("Initialized logging");      let options = poise::FrameworkOptions {          commands: vec![              help(), @@ -67,10 +74,15 @@ async fn main() {              commands::actions::hug(),              commands::pony::randpony(),              commands::pony::tpony(), +            commands::pony::ponybyid(),              commands::osu::osup(),              commands::osu::osubm(),              poise::Command { -                subcommands: vec![commands::reactionroles::init(), commands::reactionroles::add(), commands::reactionroles::del(),], +                subcommands: vec![ +                    commands::reactionroles::init(), +                    commands::reactionroles::add(), +                    commands::reactionroles::del(), +                ],                  ..commands::reactionroles::rroles()              },          ],  | 
