cbg_core/
lib.rs

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