1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
use crate::{colors, consts, Context, Error};
use log::*;
use once_cell::sync::Lazy;
use poise::serenity_prelude::GuildId;
use rand::seq::SliceRandom;
use url::Url;
pub fn parse_snowflake_from_env<T, F: Fn(u64) -> T>(key: &str, f: F) -> Option<T> {
std::env::var(key).ok().and_then(|v| v.parse().map(&f).ok())
}
pub fn parse_snowflakes_from_env<T, F: Fn(u64) -> T>(key: &str, f: F) -> Option<Vec<T>> {
std::env::var(key).ok().and_then(|gs| {
gs.split(',')
.map(|g| g.parse().map(&f))
.collect::<Result<Vec<_>, _>>()
.ok()
})
}
/*
* chooses a random element from an array
*/
pub fn random_choice<const N: usize>(arr: [&str; N]) -> Result<String, Error> {
let mut rng = rand::thread_rng();
if let Some(resp) = arr.choose(&mut rng) {
Ok((*resp).to_string())
} else {
Err(Into::into("couldn't choose from arr!"))
}
}
// waiting for `round_char_boundary` to stabilize
pub fn floor_char_boundary(s: &str, index: usize) -> usize {
if index >= s.len() {
s.len()
} else {
let lower_bound = index.saturating_sub(3);
let new_index = s.as_bytes()[lower_bound..=index]
.iter()
.rposition(|&b| (b as i8) >= -0x40); // b.is_utf8_char_boundary
// Can be made unsafe but whatever
lower_bound + new_index.unwrap()
}
}
pub fn is_guild_allowed(gid: GuildId) -> bool {
static ALLOWED_GUILDS: Lazy<Vec<GuildId>> = Lazy::new(|| {
parse_snowflakes_from_env("ALLOWED_GUILDS", GuildId)
.unwrap_or_else(|| vec![consts::TEAWIE_GUILD, GuildId(1091969030694375444)])
});
ALLOWED_GUILDS.contains(&gid)
}
pub async fn send_url_as_embed(ctx: Context<'_>, url: String) -> Result<(), Error> {
match Url::parse(&url) {
Ok(parsed) => {
let title = parsed
.path_segments()
.unwrap()
.last()
.unwrap_or_else(|| "wie")
.replace("%20", " ");
ctx.send(|c| {
c.embed(|e| {
e.title(title)
.image(&url)
.url(url)
.color(colors::Colors::Blue)
})
})
.await?;
}
Err(why) => {
error!("failed to parse url {}! {}", url, why);
ctx.say("i can't get that for you right now :(").await?;
}
}
Ok(())
}
|