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
Commits on Source (69)
*.db filter=lfs diff=lfs merge=lfs -text
/target/ /target/
Cargo.lock
**/*.rs.bk **/*.rs.bk
src/discord_token src/discord_token
ucc-bot.log ucc-bot.log
# Packages required to build
On ubuntu (such as using ubuntu with WSL) you will need these packages to build:
* libsqlite3-dev
* pkg-config
* libssl-dev
This diff is collapsed.
...@@ -5,16 +5,25 @@ authors = ["tec <tec@ucc.gu.uwa.edu.au>"] ...@@ -5,16 +5,25 @@ authors = ["tec <tec@ucc.gu.uwa.edu.au>"]
edition = "2018" edition = "2018"
[dependencies] [dependencies]
base64 = "^0.11" aes = "0.6"
chrono = "^0.4.10" async-trait = "0.1.42"
lazy_static = "^1.4.0" base64 = "0.13.0"
log = "^0.4.8" block-modes = "0.7"
openssl = "^0.10" chrono = "0.4.19"
rand = "^0.7.2" diesel = { version = "1.4.5", features = ["sqlite"] }
serde = "^1.0.104"
serde_yaml = "^0.8"
serenity = "0.8.0"
simplelog = "^0.7.4"
guard = "0.5.0" guard = "0.5.0"
indexmap = { version = "1.3.1", features = ["serde-1"] } ical = "0.7.0"
rayon = "1.3.0" indexmap = { version = "1.6.1", features = ["serde-1"] }
lazy_static = "1.4.0"
ldap3 = "0.9.1"
log = "0.4.11"
rand = "0.8.1"
rayon = "1.5.0"
regex = "1.4.3"
reqwest = "0.11.0"
serde = "1.0.118"
serde_yaml = "0.8.15"
serenity = { version = "0.10.1", default-features = false, features = ["builder", "cache", "client", "gateway", "model", "http", "utils", "rustls_backend"]}
simplelog = "0.9.0"
tokio = { version = "1", features = ["full"] }
url = "2.2.0"
File added
...@@ -7,6 +7,8 @@ use std::fs; ...@@ -7,6 +7,8 @@ use std::fs;
lazy_static! { lazy_static! {
static ref CONFIG_FILE: String = fs::read_to_string("config.yml").unwrap(); static ref CONFIG_FILE: String = fs::read_to_string("config.yml").unwrap();
pub static ref CONFIG: UccbotConfig = serde_yaml::from_str(&CONFIG_FILE).unwrap(); pub static ref CONFIG: UccbotConfig = serde_yaml::from_str(&CONFIG_FILE).unwrap();
static ref SECRETS_FILE: String = fs::read_to_string("secrets.yml").unwrap();
pub static ref SECRETS: UccbotSecrets = serde_yaml::from_str(&SECRETS_FILE).unwrap();
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
...@@ -15,12 +17,15 @@ pub struct UccbotConfig { ...@@ -15,12 +17,15 @@ pub struct UccbotConfig {
pub main_channel: id::ChannelId, pub main_channel: id::ChannelId,
pub welcome_channel: id::ChannelId, pub welcome_channel: id::ChannelId,
pub announcement_channel: id::ChannelId, pub announcement_channel: id::ChannelId,
pub bot_id: u64, pub readme_channel: id::ChannelId,
pub bot_id: id::UserId,
pub ical_url: Option<String>,
pub vote_pool_size: i8, pub vote_pool_size: i8,
pub vote_role: u64, pub vote_role: u64,
pub tiebreaker_role: u64, pub tiebreaker_role: u64,
pub unregistered_member_role: u64, pub unregistered_member_role: u64,
pub registered_member_role: u64, pub registered_member_role: u64,
pub expired_member_role: u64,
pub command_prefix: String, pub command_prefix: String,
pub for_vote: String, pub for_vote: String,
pub against_vote: String, pub against_vote: String,
...@@ -29,6 +34,12 @@ pub struct UccbotConfig { ...@@ -29,6 +34,12 @@ pub struct UccbotConfig {
pub disapprove_react: String, pub disapprove_react: String,
pub unsure_react: String, pub unsure_react: String,
pub react_role_messages: Vec<ReactionMapping>, pub react_role_messages: Vec<ReactionMapping>,
#[serde(default = "ldap_bind_address")]
pub bind_address: String,
}
pub fn ldap_bind_address() -> String {
"ldaps://samson.ucc.asn.au:636".to_string()
} }
impl UccbotConfig { impl UccbotConfig {
...@@ -44,6 +55,12 @@ impl UccbotConfig { ...@@ -44,6 +55,12 @@ impl UccbotConfig {
} }
} }
#[derive(Debug, Deserialize)]
pub struct UccbotSecrets {
pub ldap_pass: String,
pub discord_token: String,
}
pub type ReactRoleMap = IndexMap<String, id::RoleId>; pub type ReactRoleMap = IndexMap<String, id::RoleId>;
#[derive(Debug, Deserialize, Clone)] #[derive(Debug, Deserialize, Clone)]
......
...@@ -2,6 +2,7 @@ server_id: 606351521117896704 # general ...@@ -2,6 +2,7 @@ server_id: 606351521117896704 # general
main_channel: 606351521117896706 # the-corner main_channel: 606351521117896706 # the-corner
welcome_channel: 606351613816209418 # general welcome_channel: 606351613816209418 # general
announcement_channel: 606351521117896706 # the-corner announcement_channel: 606351521117896706 # the-corner
readme_channel: 606351613816209418 # general
bot_id: 607078903969742848 bot_id: 607078903969742848
...@@ -10,6 +11,7 @@ vote_role: 607478818038480937 # Vote Role ...@@ -10,6 +11,7 @@ vote_role: 607478818038480937 # Vote Role
tiebreaker_role: 607509283483025409 # tie-breaker tiebreaker_role: 607509283483025409 # tie-breaker
unregistered_member_role: 608282247350714408 # unregistered unregistered_member_role: 608282247350714408 # unregistered
registered_member_role: 608282133118582815 # registered registered_member_role: 608282133118582815 # registered
expired_member_role: 607479030370926613 # registered
command_prefix: "!" command_prefix: "!"
for_vote: "👍" for_vote: "👍"
......
...@@ -2,14 +2,17 @@ server_id: 264401248676085760 # ucc ...@@ -2,14 +2,17 @@ server_id: 264401248676085760 # ucc
main_channel: 264401248676085760 # ucc main_channel: 264401248676085760 # ucc
welcome_channel: 606750983699300372 # welcome welcome_channel: 606750983699300372 # welcome
announcement_channel: 264411219627212801 # committee announcement_channel: 264411219627212801 # committee
readme_channel: 674252245008908298 # readme
bot_id: 635407267881156618 bot_id: 635407267881156618
ical_url: "https://calendar.google.com/calendar/ical/rb44is9l4dftsnk6lmf1qske6g%40group.calendar.google.com/public/basic.ics"
vote_pool_size: 7 # 4 exec + 3 ocm vote_pool_size: 8 # 4 exec + Fresher rep + 3 ocm
vote_role: 269817189966544896 # @committee vote_role: 269817189966544896 # @committee
tiebreaker_role: 635370432568098817 # @Presiding Presidenterino tiebreaker_role: 0 # No tiebreak apparently 635370432568098817 # @Presiding Presidenterino
unregistered_member_role: 0 # does not exist unregistered_member_role: 674641042464833548 # @unregistered
registered_member_role: 0 # does not exist registered_member_role: 692754285557055490 # @member
expired_member_role: 692754285557055490 # @member
command_prefix: "!" command_prefix: "!"
...@@ -21,12 +24,27 @@ disapprove_react: "⬇" ...@@ -21,12 +24,27 @@ disapprove_react: "⬇"
unsure_react: "❔" unsure_react: "❔"
react_role_messages: react_role_messages:
- message: 674254534859554837 # Club-related - message: 674652973103579225 # Intro
- message: 674653014119809025 # Club-related
mapping: mapping:
uwa: 674254888221278226 uwa: 674254888221278226
uccl: 674255044006117386 🥤: 691852097003585577
cpu: 674255083063738368 cpu: 674255083063738368
- message: 674254563083288590 # Operating System 🎮: 691852441091833896
🤖: 696241187035676763
📐: 696241431550885888
🧬: 696241817397624862
: 696241928492286044
🧮: 696242272844382209
💸: 696242320609378345
📚: 696257213068607518
🎨: 696242397407084614
: 696242439962230854
🌥️: 696242479527100506
: 696242521738838016
🌤: 696242572288589864
: 696242617301860403
- message: 674653030817464370 # Operating System
mapping: mapping:
win10: 674255085307691039 win10: 674255085307691039
capple: 674255209916137492 capple: 674255209916137492
...@@ -35,7 +53,7 @@ react_role_messages: ...@@ -35,7 +53,7 @@ react_role_messages:
fedora: 674260517858181122 fedora: 674260517858181122
linux: 674255299494019093 linux: 674255299494019093
bsd: 674255522433859604 bsd: 674255522433859604
- message: 674254593127088148 # Editor - message: 674653049578455060 # Editor
mapping: mapping:
vim: 674255633356423208 vim: 674255633356423208
emacs: 674255739061010443 emacs: 674255739061010443
...@@ -44,7 +62,8 @@ react_role_messages: ...@@ -44,7 +62,8 @@ react_role_messages:
atom_: 674255748426891274 atom_: 674255748426891274
intellij: 674255748959567901 intellij: 674255748959567901
npp: 674255750297812993 npp: 674255750297812993
- message: 674254633929277440 # Programming eclipse: 696281046924394526
- message: 674653069526695946 # Programming (1)
mapping: mapping:
html: 674255751031685130 html: 674255751031685130
css: 674255751707099136 css: 674255751707099136
...@@ -56,6 +75,8 @@ react_role_messages: ...@@ -56,6 +75,8 @@ react_role_messages:
julia: 674255755305680901 julia: 674255755305680901
matlab: 674255755809128448 matlab: 674255755809128448
mathematica: 674255756320833536 mathematica: 674255756320833536
- message: 674653087075532810 # Programming (2)
mapping:
c_: 674256084403224673 c_: 674256084403224673
cpp: 674256084826849281 cpp: 674256084826849281
csharp: 674256086261563442 csharp: 674256086261563442
...@@ -65,7 +86,12 @@ react_role_messages: ...@@ -65,7 +86,12 @@ react_role_messages:
haskell: 674256088861769738 haskell: 674256088861769738
ruby: 674256089742835712 ruby: 674256089742835712
scala: 674256090321387530 scala: 674256090321387530
go: 674256091441397761
lua: 674256090795474944 lua: 674256090795474944
go: 674256091441397761
tex: 674256092187983897 tex: 674256092187983897
git: 674256093064593439 git: 674256093064593439
- message: 674653104666312704 # games
mapping:
et: 728997559061708922
factorio: 728997562710884373
minecraft: 728997565496033320
...@@ -13,6 +13,7 @@ vote_role: 607478818038480937 ...@@ -13,6 +13,7 @@ vote_role: 607478818038480937
tiebreaker_role: 607509283483025409 tiebreaker_role: 607509283483025409
unregistered_member_role: 608282247350714408 unregistered_member_role: 608282247350714408
registered_member_role: 608282133118582815 registered_member_role: 608282133118582815
expired_member_role: 0
command_prefix: "!" command_prefix: "!"
for_vote: "👍" for_vote: "👍"
......
use diesel::prelude::*;
use diesel::result::Error;
use diesel::sqlite::SqliteConnection;
// TODO reuse DB connection, using r2d2 or something
use crate::ldap::*;
#[table_name = "members"]
#[derive(Queryable, AsChangeset, Insertable)]
pub struct Member {
pub discord_id: i64,
pub tla: Option<String>,
pub username: String,
pub member_since: Option<String>,
pub name: Option<String>,
pub biography: Option<String>,
pub github: Option<String>,
pub photo: Option<String>,
pub website: Option<String>,
pub study: Option<String>,
}
table! {
members (discord_id) {
discord_id -> BigInt,
tla -> Nullable<Text>,
username -> Text,
member_since -> Nullable<Text>,
name -> Nullable<Text>,
biography -> Nullable<Text>,
github -> Nullable<Text>,
photo -> Nullable<Text>,
website -> Nullable<Text>,
study -> Nullable<Text>,
}
}
pub fn db_connection() -> SqliteConnection {
SqliteConnection::establish("state.db").expect("Failed to connect to sqlite DB")
}
pub fn add_member(discord_id: &u64, username: &str) -> Member {
let ldap_user = ldap_search(username);
let name = ldap_user.as_ref().map(|u| u.name.clone());
let tla_user = tla_search(username);
let tla = tla_user.as_ref().map(|u| u.tla.clone()).flatten();
let new_member = Member {
discord_id: *discord_id as i64,
username: username.to_string(),
name: name.clone(),
tla: tla,
member_since: None,
biography: None,
github: None,
photo: None,
website: None,
study: None,
};
diesel::insert_into(members::table)
.values(&new_member)
.execute(&db_connection())
.expect("Failed to add member to DB");
info!(
"{} added to member DB",
name.unwrap_or(discord_id.to_string())
);
new_member
}
#[allow(dead_code)] // remove this if you start using it
pub fn update_member(discord_id: &u64, member: Member) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(&member)
.execute(&db_connection())
}
pub fn username_exists(username: &str) -> bool {
get_member_info_from_username(username).is_ok()
}
pub fn get_member_info(discord_id: &u64) -> Result<Member, Error> {
members::table
.find(*discord_id as i64)
.first(&db_connection())
}
pub fn get_member_info_from_username(username: &str) -> Result<Member, Error> {
members::table
.filter(members::username.eq(username))
.first(&db_connection())
}
pub fn get_member_info_from_tla(tla: &str) -> Result<Member, Error> {
members::table
.filter(members::tla.eq(tla))
.first(&db_connection())
}
pub fn set_member_bio(discord_id: &u64, bio: Option<&str>) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(members::biography.eq(bio))
.execute(&db_connection())
}
pub fn set_member_git(discord_id: &u64, git: Option<&str>) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(members::github.eq(git))
.execute(&db_connection())
}
pub fn set_member_photo(discord_id: &u64, url: Option<&str>) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(members::photo.eq(url))
.execute(&db_connection())
}
pub fn set_member_website(discord_id: &u64, url: Option<&str>) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(members::website.eq(url))
.execute(&db_connection())
}
pub fn set_member_study(discord_id: &u64, study: Option<&str>) -> Result<usize, Error> {
diesel::update(members::table.find(*discord_id as i64))
.set(members::study.eq(study))
.execute(&db_connection())
}
use crate::config::{CONFIG, SECRETS};
use ldap3::{LdapConn, LdapConnSettings, Scope, SearchEntry};
#[derive(Debug)]
pub struct LDAPUser {
pub username: String,
pub name: String,
pub when_created: String,
pub login_shell: String,
}
pub fn ldap_search(username: &str) -> Option<LDAPUser> {
let settings = LdapConnSettings::new().set_no_tls_verify(true);
let mut ldap =
LdapConn::with_settings(settings, &CONFIG.bind_address).expect("Unable to connect to LDAP");
ldap.simple_bind(
"cn=ucc-discord-bot,cn=Users,dc=ad,dc=ucc,dc=gu,dc=uwa,dc=edu,dc=au",
&SECRETS.ldap_pass,
)
.expect("Unable to attempt to bind to LDAP")
.success()
.expect("Unable to bind to LDAP");
let (rs, _res) = ldap
.search(
"cn=Users,dc=ad,dc=ucc,dc=gu,dc=uwa,dc=edu,dc=au",
Scope::Subtree,
&format!("(cn={})", ldap3::ldap_escape(username)),
vec!["when_created", "displayName", "name", "loginShell"],
)
.expect("LDAP error")
.success()
.expect("LDAP search error");
if rs.is_empty() {
return None;
}
let result = SearchEntry::construct(rs[0].clone()).attrs;
Some(LDAPUser {
username: result
.get("name")
.expect("LDAP failed to get 'name' field")
.join(""),
name: result
.get("displayName")
.expect("LDAP failed to get 'displayName' field")
.join(""),
when_created: "".to_string(), // result
// .get("whenCreated")
// .expect("LDAP failed to get 'whenCreated' field")
// .join(""),
login_shell: result
.get("loginShell")
.expect("LDAP failed to get 'loginShell' field")
.join(""),
})
}
pub fn ldap_exists(username: &str) -> bool {
ldap_search(username).is_some()
}
#[derive(Debug)]
pub struct TLA {
pub tla: Option<String>,
pub name: String,
pub username: String,
}
pub fn tla_search(term: &str) -> Option<TLA> {
let tla_search = String::from_utf8(
std::process::Command::new("tla")
.arg(term)
.output()
.expect("failed to execute tla")
.stdout,
)
.expect("unable to parse stdout to String");
let tla_results = tla_search.split("\n").collect::<Vec<&str>>();
if tla_results.len() != 4 {
return None;
}
let mut the_tla = Some(tla_results[0].replace("TLA: ", "")[1..4].to_string());
if the_tla == Some(String::from("???")) {
the_tla = None;
}
Some(TLA {
tla: the_tla,
name: tla_results[1].replace("Name: ", ""),
username: tla_results[2].replace("Login: ", ""),
})
}
...@@ -7,202 +7,38 @@ extern crate indexmap; ...@@ -7,202 +7,38 @@ extern crate indexmap;
extern crate simplelog; extern crate simplelog;
#[macro_use] #[macro_use]
extern crate guard; extern crate guard;
#[macro_use]
extern crate diesel;
extern crate ldap3;
extern crate reqwest;
extern crate tokio;
use simplelog::*; use simplelog::*;
use std::fs::{read_to_string, File}; use std::fs::File;
use chrono::prelude::Utc; use serenity::client::Client;
use serenity::{
model::{channel, channel::Message, gateway::Ready, guild::Member},
prelude::*,
utils::MessageBuilder,
};
#[macro_use]
mod util;
mod config; mod config;
mod database;
mod ldap;
mod reaction_roles; mod reaction_roles;
mod serenity_handler;
mod token_management; mod token_management;
mod user_management; mod user_management;
mod util;
mod voting; mod voting;
use config::CONFIG; use config::SECRETS;
use reaction_roles::{add_role_by_reaction, remove_role_by_reaction}; use serenity_handler::Handler;
use util::get_string_from_react;
macro_rules! e { #[tokio::main]
($error: literal, $x:expr) => { async fn main() {
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]),
"verify" => user_management::Commands::verify(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]);
}
"logreact" => {
e!("Error deleting logreact prompt: {:?}", msg.delete(&ctx));
e!(
"Error sending message {:?}",
msg.channel_id
.say(&ctx.http, "React to this to log the ID (for the next 5min)")
)
}
"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) => {
let message_type = get_message_type(&message);
if message_type == MessageType::RoleReactMessage
&& add_reaction.user_id.0 != CONFIG.bot_id
{
add_role_by_reaction(&ctx, message, add_reaction);
return;
}
if message.author.id.0 != CONFIG.bot_id || add_reaction.user_id == CONFIG.bot_id {
return;
}
match message_type {
MessageType::Motion => {
voting::reaction_add(ctx, add_reaction);
}
MessageType::LogReact => {
let react_user = add_reaction.user(&ctx).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);
e!(
"Error sending message: {:?}",
message.channel_id.say(&ctx.http, msg.build())
);
}
_ => {}
}
}
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) => {
let message_type = get_message_type(&message);
if message_type == MessageType::RoleReactMessage
&& removed_reaction.user_id != CONFIG.bot_id
{
remove_role_by_reaction(&ctx, message, removed_reaction);
return;
}
if message.author.id.0 != CONFIG.bot_id || removed_reaction.user_id == CONFIG.bot_id
{
return;
}
if message_type == MessageType::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, ctx: Context, ready: Ready) {
info!("{} is connected!", ready.user.name);
reaction_roles::sync_all_role_reactions(&ctx);
}
fn resume(&self, ctx: Context, _: serenity::model::event::ResumedEvent) {
reaction_roles::sync_all_role_reactions(&ctx);
}
}
fn main() {
CombinedLogger::init(vec![ CombinedLogger::init(vec![
TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed).unwrap(), TermLogger::new(LevelFilter::Info, Config::default(), TerminalMode::Mixed),
WriteLogger::new( WriteLogger::new(
LevelFilter::Info, LevelFilter::Info,
Config::default(), Config::default(),
...@@ -211,55 +47,21 @@ fn main() { ...@@ -211,55 +47,21 @@ fn main() {
]) ])
.unwrap(); .unwrap();
// Configure the client with your Discord bot token in the environment. // ical::fetch_latest_ical().wait();
let token = read_to_string("discord_token").unwrap();
// Create a new instance of the Client, logging in as a bot. This will // 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 // automatically prepend your bot token with "Bot ", which is a requirement
// by Discord for bot users. // 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. // Finally, start a single shard, and start listening to events.
// //
// Shards will automatically attempt to reconnect, and will perform // Shards will automatically attempt to reconnect, and will perform
// exponential backoff until it reconnects. // exponential backoff until it reconnects.
if let Err(why) = client.start() { if let Err(why) = client.start().await {
error!("Client error: {:?}", why); error!("Client error: {:?}", why);
} }
} }
#[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 crate::config::{ReactRoleMap, CONFIG}; use crate::config::{ReactRoleMap, CONFIG};
use crate::util::{get_react_from_string, get_string_from_react}; use crate::util::{get_react_from_string, get_string_from_react};
use rayon::prelude::*;
use serenity::{ use serenity::{
client::Context, client::Context,
model::{channel::Message, channel::Reaction, id::RoleId, id::UserId}, model::{channel::Message, channel::Reaction, id::RoleId, id::UserId},
...@@ -8,19 +7,12 @@ use serenity::{ ...@@ -8,19 +7,12 @@ use serenity::{
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use std::iter::FromIterator; use std::iter::FromIterator;
macro_rules! e { pub async fn add_role_by_reaction(ctx: &Context, msg: Message, added_reaction: Reaction) {
($error: literal, $x:expr) => {
match $x {
Ok(_) => (),
Err(why) => error!($error, why),
}
};
}
pub fn add_role_by_reaction(ctx: &Context, msg: Message, added_reaction: Reaction) {
let user = added_reaction let user = added_reaction
.user_id .user_id
.unwrap()
.to_user(ctx) .to_user(ctx)
.await
.expect("Unable to get user"); .expect("Unable to get user");
if let Some(role_id) = CONFIG if let Some(role_id) = CONFIG
.react_role_messages .react_role_messages
...@@ -36,24 +28,29 @@ pub fn add_role_by_reaction(ctx: &Context, msg: Message, added_reaction: Reactio ...@@ -36,24 +28,29 @@ pub fn add_role_by_reaction(ctx: &Context, msg: Message, added_reaction: Reactio
user.name, user.name,
role_id role_id
.to_role_cached(ctx) .to_role_cached(ctx)
.await
.expect("Unable to get role") .expect("Unable to get role")
.name .name
); );
ctx.http ctx.http
.add_member_role( .add_member_role(
CONFIG.server_id, CONFIG.server_id,
added_reaction.user_id.0, *added_reaction.user_id.unwrap().as_u64(),
*role_id.as_u64(), *role_id.as_u64(),
) )
.await
.ok(); .ok();
} else { } else {
warn!("{} provided invalid react for role", user.name); warn!("{} provided invalid react for role", user.name);
e!("Unable to delete react: {:?}", added_reaction.delete(ctx)); e!(
"Unable to delete react: {:?}",
added_reaction.delete(ctx).await
);
} }
} }
pub fn remove_role_by_reaction(ctx: &Context, msg: Message, removed_reaction: Reaction) { pub async fn remove_role_by_reaction(ctx: &Context, msg: Message, removed_reaction: Reaction) {
CONFIG let role_id = CONFIG
.react_role_messages .react_role_messages
.iter() .iter()
.find(|rrm| rrm.message == msg.id) .find(|rrm| rrm.message == msg.id)
...@@ -61,30 +58,31 @@ pub fn remove_role_by_reaction(ctx: &Context, msg: Message, removed_reaction: Re ...@@ -61,30 +58,31 @@ pub fn remove_role_by_reaction(ctx: &Context, msg: Message, removed_reaction: Re
let react_as_string = get_string_from_react(&removed_reaction.emoji); let react_as_string = get_string_from_react(&removed_reaction.emoji);
reaction_mapping.mapping.get(&react_as_string) reaction_mapping.mapping.get(&react_as_string)
}) })
.and_then(|role_id| { .unwrap();
info!( info!(
"{} requested removal of role '{}'", "{} requested removal of role '{}'",
msg.author.name, msg.author.name,
role_id role_id
.to_role_cached(ctx) .to_role_cached(ctx)
.expect("Unable to get role") .await
.name .expect("Unable to get role")
); .name
ctx.http );
.remove_member_role( ctx.http
CONFIG.server_id, .remove_member_role(
removed_reaction.user_id.0, CONFIG.server_id,
*role_id.as_u64(), *removed_reaction.user_id.unwrap().as_u64(),
) *role_id.as_u64(),
.ok() )
}); .await
.ok();
} }
pub fn sync_all_role_reactions(ctx: &Context) { pub async fn sync_all_role_reactions(ctx: &Context) {
info!("Syncing roles to reactions"); info!("Syncing roles to reactions");
let messages_with_role_mappings = get_all_role_reaction_message(ctx); let messages_with_role_mappings = get_all_role_reaction_message(ctx);
info!(" Sync: reaction messages fetched"); info!(" Sync: reaction messages fetched");
let guild = ctx.http.get_guild(CONFIG.server_id).unwrap(); let guild = ctx.http.get_guild(CONFIG.server_id).await.unwrap();
info!(" Sync: guild fetched"); info!(" Sync: guild fetched");
// this method supports paging, but we probably don't need it since the server only has a couple of // 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 // hundred members. the Reaction.users() method can apparently only retrieve 100 users at once, but
...@@ -92,18 +90,17 @@ pub fn sync_all_role_reactions(ctx: &Context) { ...@@ -92,18 +90,17 @@ pub fn sync_all_role_reactions(ctx: &Context) {
let mut all_members = ctx let mut all_members = ctx
.http .http
.get_guild_members(CONFIG.server_id, Some(1000), None) .get_guild_members(CONFIG.server_id, Some(1000), None)
.await
.unwrap(); .unwrap();
all_members.retain(|m| m.user_id() != CONFIG.bot_id); all_members.retain(|m| m.user.id != CONFIG.bot_id);
info!(" Sync: all members fetched"); info!(" Sync: all members fetched");
let mut roles_to_add: HashMap<UserId, Vec<RoleId>> = let mut roles_to_add: HashMap<UserId, Vec<RoleId>> =
HashMap::from_iter(all_members.iter().map(|m| (m.user_id(), Vec::new()))); HashMap::from_iter(all_members.iter().map(|m| (m.user.id, Vec::new())));
let mut roles_to_remove: HashMap<UserId, Vec<RoleId>> = let mut roles_to_remove: HashMap<UserId, Vec<RoleId>> =
HashMap::from_iter(all_members.iter().map(|m| (m.user_id(), Vec::new()))); HashMap::from_iter(all_members.iter().map(|m| (m.user.id, Vec::new())));
let mut i = 0; for (i, (message, mapping)) in messages_with_role_mappings.await.iter().enumerate() {
for (message, mapping) in messages_with_role_mappings {
i += 1;
info!(" Sync: prossessing message #{}", i); info!(" Sync: prossessing message #{}", i);
for react in &message.reactions { for react in &message.reactions {
let react_as_string = get_string_from_react(&react.reaction_type); let react_as_string = get_string_from_react(&react.reaction_type);
...@@ -114,18 +111,30 @@ pub fn sync_all_role_reactions(ctx: &Context) { ...@@ -114,18 +111,30 @@ pub fn sync_all_role_reactions(ctx: &Context) {
" message #{}: Removing non-role react '{}'", " message #{}: Removing non-role react '{}'",
i, react_as_string i, react_as_string
); );
for _illegal_react in for illegal_react_user in &message
&message.reaction_users(ctx, react.reaction_type.clone(), Some(100), None) .reaction_users(&ctx.http, react.reaction_type.clone(), Some(100), None)
.await
.unwrap_or(vec![])
{ {
warn!(" need to implement react removal"); 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 { for (react, role) in *mapping {
info!(" message #{}: processing react '{}'", i, react); info!(" message #{}: processing react '{}'", i, react);
// TODO: proper pagination for the unlikely scenario that there are more than 100 (255?) reactions? // 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 reaction_type = get_react_from_string(react.clone(), guild.clone());
let reactors = message let reactors = message
.reaction_users(ctx.http.clone(), reaction_type.clone(), Some(100), None) .reaction_users(ctx.http.clone(), reaction_type.clone(), Some(100), None)
.await
.unwrap(); .unwrap();
let reactor_ids: HashSet<UserId> = HashSet::from_iter(reactors.iter().map(|r| r.id)); let reactor_ids: HashSet<UserId> = HashSet::from_iter(reactors.iter().map(|r| r.id));
...@@ -133,12 +142,12 @@ pub fn sync_all_role_reactions(ctx: &Context) { ...@@ -133,12 +142,12 @@ pub fn sync_all_role_reactions(ctx: &Context) {
if !reactor_ids.contains(&UserId::from(CONFIG.bot_id)) { if !reactor_ids.contains(&UserId::from(CONFIG.bot_id)) {
e!( e!(
"Unable to add reaction, {:?}", "Unable to add reaction, {:?}",
message.react(ctx, reaction_type) message.react(ctx, reaction_type).await
); );
} }
for member in all_members.clone() { for member in all_members.clone() {
let user_id = &member.user_id(); let user_id = &member.user.id;
if reactor_ids.contains(&user_id) { if reactor_ids.contains(&user_id) {
if !member.roles.iter().any(|r| r == role) { if !member.roles.iter().any(|r| r == role) {
roles_to_add.get_mut(&user_id).unwrap().push(*role); roles_to_add.get_mut(&user_id).unwrap().push(*role);
...@@ -155,10 +164,13 @@ pub fn sync_all_role_reactions(ctx: &Context) { ...@@ -155,10 +164,13 @@ pub fn sync_all_role_reactions(ctx: &Context) {
if !roles.is_empty() { if !roles.is_empty() {
let mut member = all_members let mut member = all_members
.iter() .iter()
.find(|m| m.user_id() == user_id) .find(|m| m.user.id == user_id)
.unwrap() .unwrap()
.clone(); .clone();
member.add_roles(ctx.http.clone(), &roles[..]).unwrap(); member
.add_roles(ctx.http.clone(), &roles[..])
.await
.unwrap();
} }
} }
info!(" Sync: (any) missing roles added"); info!(" Sync: (any) missing roles added");
...@@ -166,36 +178,36 @@ pub fn sync_all_role_reactions(ctx: &Context) { ...@@ -166,36 +178,36 @@ pub fn sync_all_role_reactions(ctx: &Context) {
if !roles.is_empty() { if !roles.is_empty() {
let mut member = all_members let mut member = all_members
.iter() .iter()
.find(|m| m.user_id() == user_id) .find(|m| m.user.id == user_id)
.unwrap() .unwrap()
.clone(); .clone();
member.remove_roles(ctx.http.clone(), &roles[..]).unwrap(); member
.remove_roles(ctx.http.clone(), &roles[..])
.await
.unwrap();
} }
} }
info!(" Sync: (any) superflous roles removed"); info!(" Sync: (any) superflous roles removed");
info!("Role reaction sync complete"); info!("Role reaction sync complete");
} }
fn get_all_role_reaction_message(ctx: &Context) -> Vec<(Message, &'static ReactRoleMap)> { async fn get_all_role_reaction_message(ctx: &Context) -> Vec<(Message, &'static ReactRoleMap)> {
let guild = ctx.http.get_guild(CONFIG.server_id).unwrap(); let guild = ctx.http.get_guild(CONFIG.server_id).await.unwrap();
info!(" Find role-react message: guild determined"); info!(" Find role-react message: guild determined");
let channels = ctx.http.get_channels(*guild.id.as_u64()).unwrap(); let channels = ctx.http.get_channels(*guild.id.as_u64()).await.unwrap();
info!(" Find role-react message: channels determined"); info!(" Find role-react message: channels determined");
let http = ctx.http.clone(); let http = ctx.http.clone();
channels let mut v = Vec::new();
.par_iter() for channel in channels {
.flat_map(|channel| { for reaction in CONFIG.react_role_messages.iter() {
// since we don't know which channels the messages are in, we check every combination if let Some(m) = http
// of message and channel and ignore the bad matches using .ok() and .filter_map() .get_message(*channel.id.as_u64(), *reaction.message.as_u64())
let h = http.clone(); // thread-local copy .await
CONFIG .ok()
.react_role_messages {
.par_iter() v.push((m, &reaction.mapping))
.filter_map(move |rrm| { }
h.get_message(*channel.id.as_u64(), *rrm.message.as_u64()) }
.ok() }
.map(|m| (m, &rrm.mapping)) v
})
})
.collect()
} }
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 base64;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};
use chrono::{prelude::Utc, DateTime}; use chrono::{prelude::Utc, DateTime};
use openssl::symm::{decrypt, encrypt, Cipher};
use rand::Rng; use rand::Rng;
use serenity::model::user::User; use serenity::model::user::User;
use std::str; use std::str;
type Aes128Cbc = Cbc<Aes128, Pkcs7>;
pub static TOKEN_LIFETIME: i64 = 300; // 5 minutes
lazy_static! { lazy_static! {
static ref KEY: [u8; 32] = rand::thread_rng().gen::<[u8; 32]>(); static ref KEY: [u8; 32] = rand::thread_rng().gen::<[u8; 32]>();
static ref CIPHER: Cipher = Cipher::aes_256_cbc(); 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 { fn text_encrypt(plaintext: &str) -> String {
let iv: &[u8; 16] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; base64::encode(CIPHER.clone().encrypt_vec(plaintext.as_bytes()))
let encrypted_vec =
encrypt(*CIPHER, &*KEY, Some(iv), plaintext.as_bytes()).expect("encryption failed");
base64::encode(encrypted_vec.as_slice())
} }
fn text_decrypt(ciphertext: &str) -> Option<String> { fn text_decrypt(ciphertext: &str) -> Option<String> {
let iv: &[u8; 16] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
guard!(let Ok(cipher_vec) = base64::decode(ciphertext) else { guard!(let Ok(cipher_vec) = base64::decode(ciphertext) else {
warn!("Unable to decode base64 text"); warn!("Unable to decode base64 text");
return None return None
}); });
guard!(let Ok(decrypted_vec) = decrypt(*CIPHER, &*KEY, Some(iv), &cipher_vec) else { guard!(let Ok(decrypted_vec) = CIPHER.clone().decrypt_vec(&cipher_vec) else {
warn!("Text decryption failed"); warn!("Text decryption failed");
return None return None
}); });
...@@ -76,7 +79,7 @@ pub fn parse_token(discord_user: &User, encrypted_token: &str) -> Result<String, ...@@ -76,7 +79,7 @@ pub fn parse_token(discord_user: &User, encrypted_token: &str) -> Result<String,
return Err(TokenError::DiscordIdMismatch); return Err(TokenError::DiscordIdMismatch);
} }
let time_delta_seconds = Utc::now().timestamp() - token_timestamp.timestamp(); let time_delta_seconds = Utc::now().timestamp() - token_timestamp.timestamp();
if time_delta_seconds > 5 * 60 { if time_delta_seconds > TOKEN_LIFETIME {
warn!( warn!(
"... attempt failed : token expired ({} seconds old)", "... attempt failed : token expired ({} seconds old)",
time_delta_seconds time_delta_seconds
......
This diff is collapsed.
use serenity::model::{channel::ReactionType, guild::PartialGuild}; use std::str::FromStr;
use serenity::model::{channel::ReactionType, guild::PartialGuild, misc::EmojiIdentifier};
pub fn get_string_from_react(react: &ReactionType) -> String { pub fn get_string_from_react(react: &ReactionType) -> String {
match react { match react {
...@@ -17,7 +19,46 @@ pub fn get_react_from_string(string: String, guild: PartialGuild) -> ReactionTyp ...@@ -17,7 +19,46 @@ pub fn get_react_from_string(string: String, guild: PartialGuild) -> ReactionTyp
.values() .values()
.find(|e| e.name == string) .find(|e| e.name == string)
.map_or_else( .map_or_else(
|| ReactionType::from(string), // unicode emoji || {
ReactionType::from(EmojiIdentifier::from_str(&string).expect(&format!(
"Emoji string \"{}\" could not be identified",
&string
)))
}, // unicode emoji
|custom_emoji| ReactionType::from(custom_emoji.clone()), |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.