Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
No results found
Show changes
......@@ -3,148 +3,42 @@ extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate indexmap;
extern crate simplelog;
#[macro_use]
extern crate guard;
#[macro_use]
extern crate diesel;
extern crate ldap3;
extern crate reqwest;
extern crate tokio;
use simplelog::*;
use std::fs::File;
use serenity::{
model::{channel, channel::Message, gateway::Ready, guild::Member},
prelude::*,
utils::MessageBuilder,
};
use serenity::client::Client;
#[macro_use]
mod util;
mod config;
mod database;
mod ldap;
mod reaction_roles;
mod serenity_handler;
mod token_management;
mod user_management;
mod voting;
use config::CONFIG;
use config::SECRETS;
use serenity_handler::Handler;
macro_rules! e {
($error: literal, $x:expr) => {
match $x {
Ok(_) => (),
Err(why) => error!($error, why),
}
};
}
struct Handler;
impl EventHandler for Handler {
// Set a handler for the `message` event - so that whenever a new message
// is received - the closure (or function) passed will be called.
//
// Event handlers are dispatched through a threadpool, and so multiple
// events can be dispatched simultaneously.
fn message(&self, ctx: Context, msg: Message) {
if !(msg.content.starts_with(CONFIG.command_prefix)) {
return;
}
let message_content: Vec<_> = msg.content[1..].splitn(2, ' ').collect();
match message_content[0] {
"say" => {
println!("{:#?}", msg.content);
}
"register" => user_management::Commands::register(ctx, msg.clone(), message_content[1]),
"join" => {
user_management::Commands::join(ctx, msg.clone(), message_content[1]);
}
"move" => {
voting::Commands::move_something(ctx, msg.clone(), message_content[1]);
}
"motion" => {
voting::Commands::motion(ctx, msg.clone(), message_content[1]);
}
"poll" => {
voting::Commands::poll(ctx, msg.clone(), message_content[1]);
}
"cowsay" => {
voting::Commands::cowsay(ctx, msg.clone(), message_content[1]);
}
"help" => {
let mut message = MessageBuilder::new();
message.push_line(format!(
"Use {}move <action> to make a circular motion",
&CONFIG.command_prefix
));
message.push_line(format!(
"Use {}poll <proposal> to see what people think about something",
&CONFIG.command_prefix
));
e!(
"Error sending message: {:?}",
msg.channel_id.say(&ctx.http, message.build())
);
}
_ => {
e!(
"Error sending message: {:?}",
msg.channel_id.say(
&ctx.http,
format!("Unrecognised command. Try {}help", &CONFIG.command_prefix)
)
);
}
}
}
fn reaction_add(&self, ctx: Context, add_reaction: channel::Reaction) {
match add_reaction.message(&ctx.http) {
Ok(message) => {
if message.author.id.0 != CONFIG.bot_id || add_reaction.user_id == CONFIG.bot_id {
return;
}
match message_type(&message) {
"motion" => {
voting::reaction_add(ctx, add_reaction);
}
_ => {}
}
}
Err(why) => error!("Failed to get react message {:?}", why),
}
}
fn reaction_remove(&self, ctx: Context, removed_reaction: channel::Reaction) {
match removed_reaction.message(&ctx.http) {
Ok(message) => {
if message.author.id.0 != CONFIG.bot_id || removed_reaction.user_id == CONFIG.bot_id {
return;
}
match message_type(&message) {
"motion" => {
voting::reaction_remove(ctx, removed_reaction);
}
_ => {}
}
}
Err(why) => error!("Failed to get react message {:?}", why),
}
}
fn guild_member_addition(
&self,
ctx: Context,
_guild_id: serenity::model::id::GuildId,
the_new_member: Member,
) {
user_management::new_member(&ctx, the_new_member);
}
// Set a handler to be called on the `ready` event. This is called when a
// shard is booted, and a READY payload is sent by Discord. This payload
// contains data like the current user's guild Ids, current user data,
// private channels, and more.
//
// In this case, just print what the current user's username is.
fn ready(&self, _: Context, ready: Ready) {
info!("{} is connected!", ready.user.name);
}
}
fn main() {
#[tokio::main]
async fn main() {
CombinedLogger::init(vec![
TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed).unwrap(),
TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed),
WriteLogger::new(
LevelFilter::Info,
Config::default(),
......@@ -153,37 +47,21 @@ fn main() {
])
.unwrap();
// Configure the client with your Discord bot token in the environment.
let token = CONFIG.discord_token;
// ical::fetch_latest_ical().wait();
// Create a new instance of the Client, logging in as a bot. This will
// automatically prepend your bot token with "Bot ", which is a requirement
// by Discord for bot users.
let mut client = Client::new(&token, Handler).expect("Err creating client");
let mut client = Client::builder(&SECRETS.discord_token)
.event_handler(Handler)
.await
.expect("Err creating client");
// Finally, start a single shard, and start listening to events.
//
// Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects.
if let Err(why) = client.start() {
if let Err(why) = client.start().await {
error!("Client error: {:?}", why);
}
}
fn message_type(message: &Message) -> &'static str {
if message.embeds.len() <= 0 {
return match message.content.splitn(2, ' ').next().unwrap() {
"Role" => "role",
_ => "misc",
};
}
let title: String = message.embeds[0].title.clone().unwrap();
let words_of_title: Vec<_> = title.splitn(2, ' ').collect();
let first_word_of_title = words_of_title[0];
return match first_word_of_title {
"Motion" => "motion",
"Poll" => "poll",
_ => "misc",
};
}
use crate::config::{ReactRoleMap, CONFIG};
use crate::util::{get_react_from_string, get_string_from_react};
use serenity::{
client::Context,
model::{channel::Message, channel::Reaction, id::RoleId, id::UserId},
};
use std::collections::{HashMap, HashSet};
use std::iter::FromIterator;
#[derive(Debug, Clone)]
struct ReactionMapping {
mapping: HashMap<serenity::model::id::EmojiId, serenity::model::id::RoleId>,
pub async fn add_role_by_reaction(ctx: &Context, msg: Message, added_reaction: Reaction) {
let user = added_reaction
.user_id
.unwrap()
.to_user(ctx)
.await
.expect("Unable to get user");
if let Some(role_id) = CONFIG
.react_role_messages
.iter()
.find(|rrm| rrm.message == msg.id)
.and_then(|reaction_mapping| {
let react_as_string = get_string_from_react(&added_reaction.emoji);
reaction_mapping.mapping.get(&react_as_string)
})
{
info!(
"{} requested role '{}'",
user.name,
role_id
.to_role_cached(ctx)
.await
.expect("Unable to get role")
.name
);
ctx.http
.add_member_role(
CONFIG.server_id,
*added_reaction.user_id.unwrap().as_u64(),
*role_id.as_u64(),
)
.await
.ok();
} else {
warn!("{} provided invalid react for role", user.name);
e!(
"Unable to delete react: {:?}",
added_reaction.delete(ctx).await
);
}
}
lazy_static! {
static ref REACTIONS_CACHE: Mutex<HashMap<serenity::model::id::MessageId, ReactionMapping>> =
Mutex::new(HashMap::new());
pub async fn remove_role_by_reaction(ctx: &Context, msg: Message, removed_reaction: Reaction) {
let role_id = CONFIG
.react_role_messages
.iter()
.find(|rrm| rrm.message == msg.id)
.and_then(|reaction_mapping| {
let react_as_string = get_string_from_react(&removed_reaction.emoji);
reaction_mapping.mapping.get(&react_as_string)
})
.unwrap();
info!(
"{} requested removal of role '{}'",
msg.author.name,
role_id
.to_role_cached(ctx)
.await
.expect("Unable to get role")
.name
);
ctx.http
.remove_member_role(
CONFIG.server_id,
*removed_reaction.user_id.unwrap().as_u64(),
*role_id.as_u64(),
)
.await
.ok();
}
pub async fn sync_all_role_reactions(ctx: &Context) {
info!("Syncing roles to reactions");
let messages_with_role_mappings = get_all_role_reaction_message(ctx);
info!(" Sync: reaction messages fetched");
let guild = ctx.http.get_guild(CONFIG.server_id).await.unwrap();
info!(" Sync: guild fetched");
// this method supports paging, but we probably don't need it since the server only has a couple of
// hundred members. the Reaction.users() method can apparently only retrieve 100 users at once, but
// this one seems to work fine when set to 1000 (I tried 10,000 but the api returned a 400)
let mut all_members = ctx
.http
.get_guild_members(CONFIG.server_id, Some(1000), None)
.await
.unwrap();
all_members.retain(|m| m.user.id != CONFIG.bot_id);
info!(" Sync: all members fetched");
let mut roles_to_add: HashMap<UserId, Vec<RoleId>> =
HashMap::from_iter(all_members.iter().map(|m| (m.user.id, Vec::new())));
let mut roles_to_remove: HashMap<UserId, Vec<RoleId>> =
HashMap::from_iter(all_members.iter().map(|m| (m.user.id, Vec::new())));
for (i, (message, mapping)) in messages_with_role_mappings.await.iter().enumerate() {
info!(" Sync: prossessing message #{}", i);
for react in &message.reactions {
let react_as_string = get_string_from_react(&react.reaction_type);
if mapping.contains_key(&react_as_string) {
continue;
}
info!(
" message #{}: Removing non-role react '{}'",
i, react_as_string
);
for illegal_react_user in &message
.reaction_users(&ctx.http, react.reaction_type.clone(), Some(100), None)
.await
.unwrap_or(vec![])
{
message
.channel_id
.delete_reaction(
&ctx.http,
message.id,
Some(illegal_react_user.id),
react.reaction_type.clone(),
)
.await
.expect("Unable to delete react");
}
}
for (react, role) in *mapping {
info!(" message #{}: processing react '{}'", i, react);
// TODO: proper pagination for the unlikely scenario that there are more than 100 (255?) reactions?
let reaction_type = get_react_from_string(react.clone(), guild.clone());
let reactors = message
.reaction_users(ctx.http.clone(), reaction_type.clone(), Some(100), None)
.await
.unwrap();
let reactor_ids: HashSet<UserId> = HashSet::from_iter(reactors.iter().map(|r| r.id));
// ensure bot has reacted
if !reactor_ids.contains(&UserId::from(CONFIG.bot_id)) {
e!(
"Unable to add reaction, {:?}",
message.react(ctx, reaction_type).await
);
}
for member in all_members.clone() {
let user_id = &member.user.id;
if reactor_ids.contains(&user_id) {
if !member.roles.iter().any(|r| r == role) {
roles_to_add.get_mut(&user_id).unwrap().push(*role);
}
} else if member.roles.iter().any(|r| r == role) {
roles_to_remove.get_mut(&user_id).unwrap().push(*role);
}
}
}
}
info!(" Sync: finished determing roles to add/remove");
for (user_id, roles) in roles_to_add {
if !roles.is_empty() {
let mut member = all_members
.iter()
.find(|m| m.user.id == user_id)
.unwrap()
.clone();
member
.add_roles(ctx.http.clone(), &roles[..])
.await
.unwrap();
}
}
info!(" Sync: (any) missing roles added");
for (user_id, roles) in roles_to_remove {
if !roles.is_empty() {
let mut member = all_members
.iter()
.find(|m| m.user.id == user_id)
.unwrap()
.clone();
member
.remove_roles(ctx.http.clone(), &roles[..])
.await
.unwrap();
}
}
info!(" Sync: (any) superflous roles removed");
info!("Role reaction sync complete");
}
async fn get_all_role_reaction_message(ctx: &Context) -> Vec<(Message, &'static ReactRoleMap)> {
let guild = ctx.http.get_guild(CONFIG.server_id).await.unwrap();
info!(" Find role-react message: guild determined");
let channels = ctx.http.get_channels(*guild.id.as_u64()).await.unwrap();
info!(" Find role-react message: channels determined");
let http = ctx.http.clone();
let mut v = Vec::new();
for channel in channels {
for reaction in CONFIG.react_role_messages.iter() {
if let Some(m) = http
.get_message(*channel.id.as_u64(), *reaction.message.as_u64())
.await
.ok()
{
v.push((m, &reaction.mapping))
}
}
}
v
}
use async_trait::async_trait;
use chrono::prelude::Utc;
use serenity::{
model::{channel, channel::Message, gateway::Ready, guild::Member},
prelude::*,
utils::MessageBuilder,
};
// use rand::seq::SliceRandom;
use crate::config::CONFIG;
use crate::ldap;
use crate::reaction_roles::{
add_role_by_reaction, remove_role_by_reaction, sync_all_role_reactions,
};
use crate::user_management;
use crate::util::get_string_from_react;
use crate::voting;
pub struct Handler;
#[async_trait]
impl EventHandler for Handler {
// Set a handler for the `message` event - so that whenever a new message
// is received - the closure (or function) passed will be called.
//
// Event handlers are dispatched through a threadpool, and so multiple
// events can be dispatched simultaneously.
async fn message(&self, ctx: Context, msg: Message) {
if !(msg.content.starts_with(&CONFIG.command_prefix)) {
if msg.content.contains(&format!("<@!{}>", CONFIG.bot_id)) // desktop mentions
|| msg.content.contains(&format!("<@{}>", CONFIG.bot_id))
// mobile mentions
{
send_message!(
msg.channel_id,
&ctx.http,
MENTION_RESPONSES[0] //.choose(&mut rand::random())
//.expect("We couldn't get any sass")
);
}
return;
}
let message_content: Vec<_> = msg.content[1..].splitn(2, ' ').collect();
let content = if message_content.len() > 1 {
message_content[1]
} else {
""
};
match message_content[0] {
"say" => println!("{:#?}", msg.content),
"register" => user_management::Commands::register(ctx, msg.clone(), content).await,
"verify" => user_management::Commands::verify(ctx, msg.clone(), content).await,
"profile" => user_management::Commands::profile(ctx, msg.clone(), content).await,
"set" => user_management::Commands::set_info(ctx, msg.clone(), content).await,
"clear" => user_management::Commands::clear_info(ctx, msg.clone(), content).await,
"move" => voting::Commands::move_something(ctx, msg.clone(), content).await,
"motion" => voting::Commands::motion(ctx, msg.clone(), content).await,
"poll" => voting::Commands::poll(ctx, msg.clone(), content).await,
"cowsay" => voting::Commands::cowsay(ctx, msg.clone(), content).await,
"source" => {
let mut mesg = MessageBuilder::new();
mesg.push(
"You want to look at my insides!? Eurgh.\nJust kidding, you can go over ",
);
mesg.push_italic("every inch");
mesg.push(" of me here: https://gitlab.ucc.asn.au/UCC/discord-bot 😉");
send_message!(msg.channel_id, &ctx.http, mesg.build());
}
"help" => {
// Plaintext version, keep in case IRC users kick up a fuss
// let mut message = MessageBuilder::new();
// message.push_line(format!(
// "Use {}move <action> to make a circular motion",
// &CONFIG.command_prefix
// ));
// message.push_line(format!(
// "Use {}poll <proposal> to see what people think about something",
// &CONFIG.command_prefix
// ));
// send_message!(msg.channel_id, &ctx.http, message.build());
let result = msg.channel_id.send_message(&ctx.http, |m| {
m.embed(|embed| {
embed.colour(serenity::utils::Colour::DARK_GREY);
embed.title("Commands for the UCC Bot");
embed.field("About", "This is UCC's own little in-house bot, please treat it nicely :)", false);
embed.field("Commitee", "`!move <text>` to make a circular motion\n\
`!poll <text>` to get people's opinions on something", false);
embed.field("Account", "`!register <ucc username>` to link your Discord and UCC account\n\
`!profile <user>` to get the profile of a user\n\
`!set <bio|git|web|photo>` to set that property of _your_ profile\n\
`!updateroles` to update your registered roles", false);
embed.field("Fun", "`!cowsay <text>` to have a cow say your words\n\
with no `<text>` it'll give you a fortune 😉", false);
embed
});
m
});
if let Err(why) = result.await {
error!("Error sending help embed: {:?}", why);
}
}
// undocumented (in !help) functins
"logreact" => {
e!(
"Error deleting logreact prompt: {:?}",
msg.delete(&ctx).await
);
send_message!(
msg.channel_id,
&ctx.http,
"React to this to log the ID (for the next 5min)"
);
}
"ldap" => send_message!(
msg.channel_id,
&ctx.http,
format!("{:?}", ldap::ldap_search(message_content[1]))
),
"tla" => send_message!(
msg.channel_id,
&ctx.http,
format!("{:?}", ldap::tla_search(message_content[1]))
),
"updateroles" => user_management::Commands::update_registered_role(ctx, msg).await,
_ => send_message!(
msg.channel_id,
&ctx.http,
format!("Unrecognised command. Try {}help", &CONFIG.command_prefix)
),
}
}
async fn reaction_add(&self, ctx: Context, add_reaction: channel::Reaction) {
match add_reaction.message(&ctx.http).await {
Ok(message) => match get_message_type(&message) {
MessageType::RoleReactMessage if add_reaction.user_id == Some(CONFIG.bot_id) => {
add_role_by_reaction(&ctx, message, add_reaction).await
}
_ if message.author.id != CONFIG.bot_id
|| add_reaction.user_id == Some(CONFIG.bot_id) => {}
MessageType::Motion => voting::reaction_add(&ctx, add_reaction).await,
MessageType::LogReact => {
let react_user = add_reaction.user(&ctx).await.unwrap();
let react_as_string = get_string_from_react(&add_reaction.emoji);
if Utc::now().timestamp() - message.timestamp.timestamp() > 300 {
warn!(
"The logreact message {} just tried to use is too old",
react_user.name
);
return;
}
info!(
"The react {} just added is {:?}. In full: {:?}",
react_user.name, react_as_string, add_reaction.emoji
);
let mut msg = MessageBuilder::new();
msg.push_italic(react_user.name);
msg.push(format!(
" wanted to know that {} is represented by ",
add_reaction.emoji,
));
msg.push_mono(react_as_string);
message
.channel_id
.say(&ctx.http, msg.build())
.await
.unwrap();
send_message!(message.channel_id, &ctx.http, msg.build());
}
_ => {}
},
Err(why) => error!("Failed to get react message {:?}", why),
}
}
async fn reaction_remove(&self, ctx: Context, removed_reaction: channel::Reaction) {
match removed_reaction.message(&ctx.http).await {
Ok(message) => match get_message_type(&message) {
MessageType::RoleReactMessage
if removed_reaction.user_id.unwrap() != CONFIG.bot_id =>
{
remove_role_by_reaction(&ctx, message, removed_reaction).await
}
_ if message.author.id != CONFIG.bot_id
|| removed_reaction.user_id.unwrap() == CONFIG.bot_id => {}
MessageType::Motion => voting::reaction_remove(&ctx, removed_reaction).await,
_ => {}
},
Err(why) => error!("Failed to get react message {:?}", why),
}
}
async fn guild_member_addition(
&self,
ctx: Context,
_guild_id: serenity::model::id::GuildId,
the_new_member: Member,
) {
user_management::new_member(&ctx, the_new_member).await
}
// Set a handler to be called on the `ready` event. This is called when a
// shard is booted, and a READY payload is sent by Discord. This payload
// contains data like the current user's guild Ids, current user data,
// private channels, and more.
//
// In this case, just print what the current user's username is.
async fn ready(&self, ctx: Context, ready: Ready) {
info!("{} is connected!", ready.user.name);
sync_all_role_reactions(&ctx).await
}
async fn resume(&self, ctx: Context, _: serenity::model::event::ResumedEvent) {
sync_all_role_reactions(&ctx).await
}
}
pub const MENTION_RESPONSES: &[&str] = &[
"Oh hello there",
"Stop bothering me. I'm busy.",
"You know, I'm trying to keep track of this place. I don't need any more distractions.",
"Don't you have better things to do?",
"(sigh) what now?",
"Yes, yes, I know I'm brilliant",
"What do I need to do to catch a break around here? Eh.",
"Mmmmhmmm. I'm still around, don't mind me.",
"You know, some people would consider this rude. Luckily I'm not one of those people. In fact, I'm not even a person.",
"Perhaps try bothering someone else for a change."
];
#[derive(Debug, PartialEq)]
enum MessageType {
Motion,
Role,
RoleReactMessage,
LogReact,
Poll,
Misc,
}
fn get_message_type(message: &Message) -> MessageType {
if CONFIG
.react_role_messages
.iter()
.any(|rrm| rrm.message == message.id)
{
return MessageType::RoleReactMessage;
}
if message.embeds.is_empty() {
// Get first word of message
return match message.content.splitn(2, ' ').next().unwrap() {
"Role" => MessageType::Role,
"React" => MessageType::LogReact,
_ => MessageType::Misc,
};
}
let title: String = message.embeds[0].title.clone().unwrap();
let words_of_title: Vec<_> = title.splitn(2, ' ').collect();
let first_word_of_title = words_of_title[0];
match first_word_of_title {
"Motion" => MessageType::Motion,
"Poll" => MessageType::Poll,
_ => MessageType::Misc,
}
}
use aes::Aes128;
use base64;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
use chrono::{prelude::Utc, DateTime};
use rand::Rng;
use serenity::model::user::User;
use std::str;
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
pub static TOKEN_LIFETIME: i64 = 300; // 5 minutes
lazy_static! {
static ref KEY: [u8; 32] = rand::thread_rng().gen::<[u8; 32]>();
static ref IV: [u8; 16] = [0; 16];
static ref CIPHER: Aes128Cbc = Aes128Cbc::new_var(KEY.as_ref(), IV.as_ref()).unwrap();
}
fn text_encrypt(plaintext: &str) -> String {
base64::encode(CIPHER.clone().encrypt_vec(plaintext.as_bytes()))
}
fn text_decrypt(ciphertext: &str) -> Option<String> {
guard!(let Ok(cipher_vec) = base64::decode(ciphertext) else {
warn!("Unable to decode base64 text");
return None
});
guard!(let Ok(decrypted_vec) = CIPHER.clone().decrypt_vec(&cipher_vec) else {
warn!("Text decryption failed");
return None
});
guard!(let Ok(decrypted_token) = str::from_utf8(decrypted_vec.as_slice()) else {
warn!("Invalid utf8 in text");
return None
});
Some(decrypted_token.to_owned())
}
pub fn generate_token(discord_user: &User, username: &str) -> String {
// if username doesn't exist : throw error
let timestamp = Utc::now().to_rfc3339();
let payload = format!(
"{},{},{}",
timestamp,
discord_user.id.0.to_string(),
username
);
info!("Token generated for {}: {}", discord_user.name, &payload);
text_encrypt(&payload)
}
#[derive(Debug)]
pub enum TokenError {
DiscordIdMismatch,
TokenExpired,
TokenInvalid,
}
impl std::fmt::Display for TokenError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
pub fn parse_token(discord_user: &User, encrypted_token: &str) -> Result<String, TokenError> {
guard!(let Some(token) = text_decrypt(encrypted_token) else {
return Err(TokenError::TokenInvalid)
});
let token_components: Vec<_> = token.splitn(3, ',').collect();
info!(
"Verification attempt from '{}'(uid: {}) for account '{}' with token from {}",
discord_user.name, token_components[1], token_components[2], token_components[0]
);
let token_timestamp =
DateTime::parse_from_rfc3339(token_components[0]).expect("Invalid date format");
let token_discord_user = token_components[1];
let token_username = token_components[2];
if token_discord_user != discord_user.id.0.to_string() {
warn!("... attempt failed : DiscordID mismatch");
return Err(TokenError::DiscordIdMismatch);
}
let time_delta_seconds = Utc::now().timestamp() - token_timestamp.timestamp();
if time_delta_seconds > TOKEN_LIFETIME {
warn!(
"... attempt failed : token expired ({} seconds old)",
time_delta_seconds
);
return Err(TokenError::TokenExpired);
}
info!(
"... verification successful (token {} seconds old)",
time_delta_seconds
);
Ok(token_username.to_owned())
}
This diff is collapsed.
use std::str::FromStr;
use serenity::model::{channel::ReactionType, guild::PartialGuild, misc::EmojiIdentifier};
pub fn get_string_from_react(react: &ReactionType) -> String {
match react {
ReactionType::Custom {
name: Some(name), ..
} => name.to_string(),
ReactionType::Custom { id, name: None, .. } => id.to_string(),
ReactionType::Unicode(name) => name.to_string(),
_ => format!("Unrecognised reaction type: {:?}", react),
}
}
pub fn get_react_from_string(string: String, guild: PartialGuild) -> ReactionType {
guild
.emojis
.values()
.find(|e| e.name == string)
.map_or_else(
|| {
ReactionType::from(EmojiIdentifier::from_str(&string).expect(&format!(
"Emoji string \"{}\" could not be identified",
&string
)))
}, // unicode emoji
|custom_emoji| ReactionType::from(custom_emoji.clone()),
)
}
#[macro_use]
macro_rules! e {
($error: literal, $x:expr) => {
match $x {
Ok(_) => (),
Err(why) => error!($error, why),
}
};
}
#[macro_use]
macro_rules! send_message {
($chan:expr, $context:expr, $message:expr) => {
match $chan.say($context, $message).await {
Ok(_) => (),
Err(why) => error!("Error sending message: {:?}", why),
}
};
}
#[allow(unused_macros)] // remove this if you start using it
#[macro_use]
macro_rules! send_delete_message {
($chan:expr, $context:expr, $message:expr) => {
match $chan.say($context, $message).await {
Ok(the_new_msg) => e!(
"Error deleting register message: {:?}",
the_new_msg.delete($context)
),
Err(why) => error!("Error sending message: {:?}", why),
}
};
}
This diff is collapsed.