cbg_core/
lib.rs

1pub mod imageops;
2pub mod jobs;
3pub mod osu;
4pub mod tetrio;
5
6pub type Error = Box<dyn std::error::Error + Send + Sync>;
7#[derive(Debug, Clone, Copy)]
8// use this struct instead of serenity color
9pub struct AverageColor {
10    red: u8,
11    green: u8,
12    blue: u8,
13}
14impl AverageColor {
15    #[cfg(feature = "discord")]
16    pub fn to_embed_color(&self) -> serenity::all::Color {
17        serenity::all::Color::from_rgb(self.red, self.green, self.blue)
18    }
19
20    pub fn new(red: u8, green: u8, blue: u8) -> Self {
21        Self { red, green, blue }
22    }
23    pub async fn from_image_url(url: &str) -> Result<AverageColor, Error> {
24        use image::{GenericImageView, load_from_memory};
25        let img_bytes = &reqwest::get(url).await?.bytes().await?;
26
27        let img = load_from_memory(img_bytes)?;
28        let (width, height) = img.dimensions();
29        let mut red = 0u64;
30        let mut green = 0u64;
31        let mut blue = 0u64;
32
33        // go through the pixels and calculate average color
34        for x in 0..width {
35            for y in 0..height {
36                let pixel = img.get_pixel(x, y).0; // Get pixel (R, G, B, A)
37                red += pixel[0] as u64;
38                green += pixel[1] as u64;
39                blue += pixel[2] as u64;
40            }
41        }
42
43        // calculate the average
44        let num_pixels = (width * height) as u64;
45        red /= num_pixels;
46        green /= num_pixels;
47        blue /= num_pixels;
48
49        Ok(AverageColor::new(red as u8, green as u8, blue as u8))
50    }
51}
52
53pub async fn pi() -> String {
54    use rand::Rng;
55    let mut pi_string = format!("{:.15}", std::f64::consts::PI); // get Pi to 15 decimal places
56
57    // VERY SMALL CHANCE to mess up a digit
58    if rand::rng().random_bool(0.000000001454) {
59        let digits: Vec<char> = pi_string.chars().collect();
60        let mut rng = rand::rng();
61
62        // pick a random index after the decimal point (skip '3' and '.')
63        let idx = rng.random_range(2..digits.len());
64        let new_digit = rng.random_range(0..10).to_string().chars().next().unwrap();
65
66        let mut new_pi_string = digits.clone();
67        new_pi_string[idx] = new_digit;
68        pi_string = new_pi_string.iter().collect();
69    }
70
71    pi_string
72}
73
74pub async fn get_random_ipv4() -> String {
75    use rand::prelude::*;
76    let mut rng = rand::rngs::StdRng::from_os_rng();
77
78    let octet1: u8 = rng.random_range(0..=255);
79    let octet2: u8 = rng.random_range(0..=255);
80    let octet3: u8 = rng.random_range(0..=255);
81    let octet4: u8 = rng.random_range(0..=255);
82
83    format!("{}.{}.{}.{}", octet1, octet2, octet3, octet4)
84}