Skip to content

Instantly share code, notes, and snippets.

@espeon
Created March 9, 2020 16:49
Show Gist options
  • Select an option

  • Save espeon/7ae5af26cb1a9349bf31c77f6746dfa9 to your computer and use it in GitHub Desktop.

Select an option

Save espeon/7ae5af26cb1a9349bf31c77f6746dfa9 to your computer and use it in GitHub Desktop.
use log::error;
use serde_json::Value;
use serenity::framework::standard::macros::command;
use serenity::framework::standard::CommandError;
use serenity::framework::standard::{Args, CommandResult};
use serenity::model::prelude::*;
use serenity::prelude::*;
static POKEMON_API_URL: &str = "https://pokeapi.co/api/v2/{ENDPOINT}/{TERM}";
cached! {
CACHE_DATA;
fn get_data(url: &'static str, endpoint: &'static str, term: String) -> Result<Value, CommandError> = {
let url = url.replace("{ENDPOINT}", &endpoint);
let url = url.replace("{TERM}", &term);
println!("{:#?}", url);
// fetch data
let client = reqwest::blocking::Client::new();
match client.get(&url).send().and_then(|x| x.json()) {
//get from url and convert to json
Ok(val) => Ok(val), //send data back as serde_json value
Err(e) => {
error!("[GRP:pokedex] Failed to fetch data: {}", e);
Err(CommandError::from(&format!("Failed to get data from given URL: {}", url)))
}
}
}
}
#[command]
#[aliases(poke, pk, pokemon)]
fn pokedex(ctx: &mut Context, msg: &Message, args: Args) -> CommandResult {
let text = 2;
let data = get_data(POKEMON_API_URL, "pokemon-species", args.rest().to_string())?;
let name = data
.pointer("/name") //where we get the data
.and_then(|x| x.as_str()) //convert to string
.unwrap_or("N/A"); //if not available, set var as "N/A"
let description = data
.pointer(&format!("/flavor_text_entries/{}/flavor_text", text.to_string())) //where we get the data
.and_then(|x| x.as_str()) //convert to string
.unwrap_or("N/A"); //if not available, set var as "N/A"
let _ = msg.channel_id.send_message(&ctx.http, |m| {
m.embed(|e| {
e.color(0x3498db)
.title(cap_first_letter(name))
.description(description)
})
});
Ok(())
}
fn cap_first_letter(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment