Skip to content
Extraits de code Groupes Projets
Vérifiée Valider db91e142 rédigé par Kubat's avatar Kubat
Parcourir les fichiers

Add little macros to make life easier

parent 8eecaff8
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
...@@ -2,7 +2,7 @@ use crate::{ ...@@ -2,7 +2,7 @@ use crate::{
cmd::package::CmdPackage, cmd::package::CmdPackage,
cmd::Cmd, cmd::Cmd,
config::{from_file as config_from_file, Config}, config::{from_file as config_from_file, Config},
return_if, log_fatal, return_if,
}; };
use futures::future::join_all; use futures::future::join_all;
use log::{error, info, warn}; use log::{error, info, warn};
...@@ -20,7 +20,6 @@ use matrix_sdk::{ ...@@ -20,7 +20,6 @@ use matrix_sdk::{
}, },
UserId, UserId,
}, },
uuid::Uuid,
Client, Result, SyncSettings, Client, Result, SyncSettings,
}; };
use std::{ use std::{
...@@ -36,6 +35,21 @@ pub struct Bot { ...@@ -36,6 +35,21 @@ pub struct Bot {
client: Option<Client>, client: Option<Client>,
} }
static GLOBAL_PKG: SyncLazy<Arc<Mutex<Vec<CmdPackage>>>> =
SyncLazy::new(|| Arc::new(Mutex::new(Vec::<CmdPackage>::new())));
macro_rules! GLOBAL_PKG_ITER {
() => {{
GLOBAL_PKG.lock().unwrap().iter()
}};
}
macro_rules! GLOBAL_PKG_LOCKED {
() => {{
GLOBAL_PKG.lock().unwrap()
}};
}
async fn join_room(room: &Invited) { async fn join_room(room: &Invited) {
info!("Autojoining room {}", room.room_id()); info!("Autojoining room {}", room.room_id());
let mut delay = 2; // seconds let mut delay = 2; // seconds
...@@ -110,12 +124,7 @@ async fn on_msg_room_event( ...@@ -110,12 +124,7 @@ async fn on_msg_room_event(
if body.starts_with("%") { if body.starts_with("%") {
if let Some(stripped) = body.strip_prefix("%") { if let Some(stripped) = body.strip_prefix("%") {
let args = stripped.split(' ').collect::<Vec<&str>>(); let args = stripped.split(' ').collect::<Vec<&str>>();
let (res, emojies) = match GLOBAL_PKG let (res, emojies) = match GLOBAL_PKG_ITER!().find(|x| x.has_command(&args)) {
.lock()
.unwrap()
.iter()
.find(|x| x.has_command(&args))
{
Some(pkg) => { Some(pkg) => {
let (res, emojies) = pkg.handle(&joined, &sender_id, args); let (res, emojies) = pkg.handle(&joined, &sender_id, args);
(res, emojies.clone()) (res, emojies.clone())
...@@ -127,14 +136,14 @@ async fn on_msg_room_event( ...@@ -127,14 +136,14 @@ async fn on_msg_room_event(
let msg = AnyMessageEventContent::RoomMessage( let msg = AnyMessageEventContent::RoomMessage(
MessageEventContent::text_reply_html(res.clone(), res, &event), MessageEventContent::text_reply_html(res.clone(), res, &event),
); );
let msg_uuid = Uuid::new_v4(); let send_id = joined.send(msg, None).await.unwrap().event_id;
let send_id = joined.send(msg, Some(msg_uuid)).await.unwrap().event_id; join_all(emojies.iter().map(|emoji| {
for emoji in emojies {
let msg_emoji = AnyMessageEventContent::Reaction(ReactionEventContent::new( let msg_emoji = AnyMessageEventContent::Reaction(ReactionEventContent::new(
Relation::new(send_id.clone(), emoji.clone()), Relation::new(send_id.clone(), emoji.clone()),
)); ));
joined.send(msg_emoji, None).await.unwrap(); joined.send(msg_emoji, None)
} }))
.await;
} }
} }
}; };
...@@ -180,18 +189,15 @@ macro_rules! register_handler_if_enabled { ...@@ -180,18 +189,15 @@ macro_rules! register_handler_if_enabled {
}}; }};
} }
static GLOBAL_PKG: SyncLazy<Arc<Mutex<Vec<CmdPackage>>>> =
SyncLazy::new(|| Arc::new(Mutex::new(Vec::<CmdPackage>::new())));
impl Bot { impl Bot {
pub fn new(config_file: String) -> Bot { pub fn new(config_file: String) -> Bot {
match config_from_file(&config_file) { match config_from_file(&config_file) {
Err(e) => { Err(e) => {
error!( log_fatal!(
"Failed to read config file '{}' with error: {}", "Failed to read config file '{}' with error: {}",
config_file, e config_file,
e
); );
abort();
} }
Ok(config) => { Ok(config) => {
info!("Using config file: {}", config_file); info!("Using config file: {}", config_file);
...@@ -257,6 +263,6 @@ impl Bot { ...@@ -257,6 +263,6 @@ impl Bot {
abort(); abort();
} }
}; };
GLOBAL_PKG.lock().unwrap().push(pkg); GLOBAL_PKG_LOCKED!().push(pkg);
} }
} }
#![allow(dead_code)] #![allow(dead_code)]
use crate::bool_to_result; use crate::{bool_to_result, log_fatal};
use log::{error, warn}; use log::warn;
use matrix_sdk::{room::Joined as JoinedRoom, ruma::UserId}; use matrix_sdk::{room::Joined as JoinedRoom, ruma::UserId};
use std::fmt; use std::fmt;
use std::{process::abort, result::Result}; use std::result::Result;
#[derive(Clone)] #[derive(Clone)]
pub enum CmdAcl { pub enum CmdAcl {
...@@ -138,8 +138,7 @@ impl CmdAcl { ...@@ -138,8 +138,7 @@ impl CmdAcl {
} else if upper == "ANY" { } else if upper == "ANY" {
CmdAcl::Any CmdAcl::Any
} else { } else {
error!("Unknown ACL: {}", string); log_fatal!("Unknown ACL: {}", string);
abort();
} }
} }
......
...@@ -3,8 +3,8 @@ ...@@ -3,8 +3,8 @@
pub mod acl; pub mod acl;
pub mod package; pub mod package;
use log::error; use crate::log_fatal;
use std::{boxed::Box, process::abort, string::String}; use std::{boxed::Box, string::String};
trait CmdFnSimple = Fn(Vec<&str>) -> bool + Send + Sync; trait CmdFnSimple = Fn(Vec<&str>) -> bool + Send + Sync;
trait CmdFnEcho = Fn(Vec<&str>) -> String + Send + Sync; trait CmdFnEcho = Fn(Vec<&str>) -> String + Send + Sync;
...@@ -34,8 +34,7 @@ impl Cmd { ...@@ -34,8 +34,7 @@ impl Cmd {
pub fn exec(&self, args: Vec<&str>) -> String { pub fn exec(&self, args: Vec<&str>) -> String {
if args.len() != self.argc as usize { if args.len() != self.argc as usize {
error!("Arg count doesn't match"); log_fatal!("Arg count doesn't match");
abort();
} }
match &self.handler { match &self.handler {
......
#![allow(dead_code)] #![allow(dead_code)]
use crate::log_fatal;
use ini::{Error::Io as IniErrIo, Error::Parse as IniErrParse, Ini, Properties as IniSection}; use ini::{Error::Io as IniErrIo, Error::Parse as IniErrParse, Ini, Properties as IniSection};
use log::{error, info, warn, LevelFilter}; use log::{error, info, warn, LevelFilter};
use std::{env, path::Path, process::abort, str::FromStr}; use std::{env, path::Path, process::abort, str::FromStr};
...@@ -110,11 +111,10 @@ pub fn check_argument_or_abort(should_write_default: bool) { ...@@ -110,11 +111,10 @@ pub fn check_argument_or_abort(should_write_default: bool) {
.to_string() .to_string()
+ ".ini"; + ".ini";
if Path::new(&default_file).exists() { if Path::new(&default_file).exists() {
error!( log_fatal!(
"Args count is {}, you need to only specify the config file for the bot", "Args count is {}, you need to only specify the config file for the bot",
env::args().len() - 1 env::args().len() - 1
); );
abort();
} else if should_write_default { } else if should_write_default {
warn!("Try to write the default config file to {}", default_file); warn!("Try to write the default config file to {}", default_file);
match write_default(&default_file) { match write_default(&default_file) {
......
#![allow(dead_code)] #![allow(dead_code, unused_imports)]
#[macro_export]
macro_rules! log_fatal {
($($arg:tt)+) => {{
use log::error;
use std::process::abort;
error!($($arg)+);
abort();
}};
}
#[macro_export] #[macro_export]
macro_rules! return_if { macro_rules! return_if {
......
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Veuillez vous inscrire ou vous pour commenter