From e5ea38b4425dbb8e5a7c7c9414f705856c85d81f Mon Sep 17 00:00:00 2001 From: Natsu Kagami Date: Thu, 16 Jan 2020 03:56:19 -0500 Subject: [PATCH] Implement announcer --- youmubot/src/commands/announcer.rs | 51 ++++++++++++++++++++++++++++++ youmubot/src/commands/mod.rs | 1 + 2 files changed, 52 insertions(+) create mode 100644 youmubot/src/commands/announcer.rs diff --git a/youmubot/src/commands/announcer.rs b/youmubot/src/commands/announcer.rs new file mode 100644 index 0000000..4e98114 --- /dev/null +++ b/youmubot/src/commands/announcer.rs @@ -0,0 +1,51 @@ +use serenity::{ + builder::CreateMessage, + framework::standard::{CommandError as Error, CommandResult}, + http::{CacheHttp, Http}, + model::id::{ChannelId, GuildId, UserId}, +}; +use std::{ + collections::HashSet, + thread::{spawn, JoinHandle}, +}; + +pub trait Announcer { + type MessageSender: for<'a, 'r> Fn(&'r mut CreateMessage<'a>) -> &'r mut CreateMessage<'a>; + + fn get_guilds(c: impl AsRef) -> Result, Error>; + fn fetch_messages(c: impl AsRef) -> Result, Error>; + + fn announce(c: impl AsRef) -> CommandResult { + let guilds: Vec<_> = Self::get_guilds(c.as_ref())?; + let member_sets = { + let mut v = Vec::with_capacity(guilds.len()); + for (guild, channel) in guilds.into_iter() { + let mut s = HashSet::new(); + for user in guild.members_iter(c.as_ref()) { + s.insert(user?.user_id()); + } + v.push((s, channel)) + } + v + }; + for (user_id, f) in Self::fetch_messages(c.as_ref())?.into_iter() { + for (members, channel) in member_sets.iter() { + if members.contains(&user_id) { + if let Err(e) = channel.send_message(c.as_ref(), &f) { + dbg!((user_id, channel, e)); + } + } + } + } + Ok(()) + } + + fn scan(c: impl CacheHttp + 'static + Send, cooldown: std::time::Duration) -> JoinHandle<()> { + spawn(move || loop { + if let Err(e) = Self::announce(c.http()) { + dbg!(e); + } + std::thread::sleep(cooldown); + }) + } +} diff --git a/youmubot/src/commands/mod.rs b/youmubot/src/commands/mod.rs index b323cbb..00925ac 100644 --- a/youmubot/src/commands/mod.rs +++ b/youmubot/src/commands/mod.rs @@ -7,6 +7,7 @@ use serenity::{ }; use std::collections::HashSet; +mod announcer; mod args; pub mod admin;