fursonabot/src/color.rs
asonix b365973fd2
Some checks failed
continuous-integration/drone/tag Build is failing
fursonabot
2022-12-30 17:27:42 -06:00

44 lines
968 B
Rust

use crate::error::AnyError;
use rand::Rng;
use reqwest::Client;
#[derive(serde::Deserialize)]
struct Color {
name: ColorName,
}
#[derive(serde::Deserialize)]
struct ColorName {
value: String,
}
#[derive(Debug)]
struct ColorFailure(String);
pub(crate) async fn generate_color(client: &Client) -> Result<String, AnyError> {
let mut rng = rand::thread_rng();
let [r, g, b]: [u8; 3] = rng.gen();
let url = format!("http://www.thecolorapi.com/id?rgb={},{},{}", r, g, b);
let response = client.get(&url).send().await?;
if !response.status().is_success() {
return Err(ColorFailure(response.text().await?).into());
}
let color: Color = response.json().await?;
Ok(color.name.value.to_lowercase())
}
impl std::fmt::Display for ColorFailure {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Failed to fetch color: {}", self.0)
}
}
impl std::error::Error for ColorFailure {}