Skip to content
Snippets Groups Projects

React improvements

Merged Stephen D requested to merge react-improvements into master
3 files
+ 57
21
Compare changes
  • Side-by-side
  • Inline
Files
3
+ 40
21
use crate::handlers::LineHandler;
use itertools::Itertools;
use phf::phf_map;
use serenity::async_trait;
use serenity::model::channel::{Message, ReactionType};
@@ -14,36 +15,54 @@ static EMOJI_MAP: phf::Map<&'static str, &'static str> = phf_map! {
"mango" => "🥭",
"banana" => "🍌",
"bee" => "🐝",
"hose" => "🐎",
"horse" => "🐎",
"hat" => "🎩"
};
fn map_lookup(msg: &str) -> Option<&'static str> {
// We lose the O(1) benefits of the hashmap
// But whatever. It doesn't need to be fast
for (k, v) in EMOJI_MAP.entries() {
if &msg == k || msg == format!("{}s", k) {
return Some(v);
}
}
None
}
#[derive(Default)]
pub struct ReactHandler;
#[async_trait]
impl LineHandler for ReactHandler {
async fn message(&self, ctx: &Context, msg: &Message) {
for (key, value) in EMOJI_MAP.entries() {
let msg_lower = format!(" {} ", msg.content.to_lowercase());
if msg_lower.contains(&format!(" {} ", key))
|| msg_lower.contains(&format!(" {}s ", key))
{
let reaction_type = match ReactionType::from_str(value) {
Ok(x) => x,
Err(x) => {
println!("Could not react: {}", x);
return;
}
};
if let Err(e) = msg.react(&ctx, reaction_type).await {
println!("Error reacting: {}", e);
// Kind of convoluted, but allows us to react in the correct order.
let groups = msg
.content
.chars()
.map(|c| match c {
'!' | '?' | ',' | '.' => ' ',
_ => c,
})
.group_by(|c| *c == ' ');
let reacts: Vec<_> = groups
.into_iter()
.filter_map(|(_, c)| map_lookup(&c.collect::<String>().to_lowercase()))
.unique()
.collect();
for r in reacts {
let reaction_type = match ReactionType::from_str(r) {
Ok(x) => x,
Err(x) => {
println!("Could not react: {}", x);
return;
}
};
if let Err(e) = msg.react(&ctx, reaction_type).await {
println!("Error reacting: {}", e);
}
}
}
}
impl Default for ReactHandler {
fn default() -> Self {
Self
}
}
Loading