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

Need a 'static package list

Will try latter to have some sort of hash map to have a separate set of
packages for different bots if needed but it's clearly not the priority
for now.
parent 2b91f3e2
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
...@@ -22,13 +22,17 @@ use matrix_sdk::{ ...@@ -22,13 +22,17 @@ use matrix_sdk::{
}, },
Client, Result, SyncSettings, Client, Result, SyncSettings,
}; };
use std::{convert::TryFrom, process::abort, sync::Mutex}; use std::{
convert::TryFrom,
lazy::SyncLazy,
process::abort,
sync::{Arc, Mutex},
};
use tokio::time::{sleep, Duration}; use tokio::time::{sleep, Duration};
pub struct Bot { pub struct Bot {
config: Config, config: Config,
client: Option<Client>, client: Option<Client>,
packages: Mutex<Vec<CmdPackage>>,
} }
async fn join_room(room: &Invited) { async fn join_room(room: &Invited) {
...@@ -92,6 +96,39 @@ async fn startup_and_log_rooms(client: &Client) { ...@@ -92,6 +96,39 @@ async fn startup_and_log_rooms(client: &Client) {
join_all(list_to_wait_for).await; join_all(list_to_wait_for).await;
} }
async fn on_msg_room_event(
ev: SyncMessageEvent<MessageEventContent>,
room: Room,
__info: Option<EncryptionInfo>,
) {
let sender_id = ev.sender.clone();
return_if!(sender_id.as_str() == room.own_user_id().as_str(), ());
if let (Room::Joined(joined), MessageType::Text(TextMessageEventContent { ref body, .. })) =
(room, ev.content.msgtype.clone())
{
if body.starts_with("%") {
if let Some(stripped) = body.strip_prefix("%") {
let args = stripped.split(' ').collect::<Vec<&str>>();
let mut res: String = format!("Command not found");
if let Some(pkg) = GLOBAL_PKG
.lock()
.unwrap()
.iter()
.find(|x| x.has_command(&args))
{
res = pkg.handle(&joined, &sender_id, args);
}
let event = ev.into_full_event(joined.room_id().clone());
let msg = AnyMessageEventContent::RoomMessage(
MessageEventContent::text_reply_html(res.clone(), res, &event),
);
joined.send(msg, None).await.unwrap();
}
}
};
}
async fn on_msg_room_reaction( async fn on_msg_room_reaction(
ev: SyncMessageEvent<ReactionEventContent>, ev: SyncMessageEvent<ReactionEventContent>,
room: Room, room: Room,
...@@ -132,6 +169,9 @@ macro_rules! register_handler_if_enabled { ...@@ -132,6 +169,9 @@ 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) {
...@@ -147,12 +187,15 @@ impl Bot { ...@@ -147,12 +187,15 @@ impl Bot {
Bot { Bot {
config: config, config: config,
client: None, client: None,
packages: Mutex::new(Vec::<CmdPackage>::new()),
} }
} }
} }
} }
pub fn get_configuration(&self) -> &Config {
&self.config
}
pub async fn connect(&mut self) -> Result<&mut Self> { pub async fn connect(&mut self) -> Result<&mut Self> {
let alice = UserId::try_from(self.config.user_name.clone())?; let alice = UserId::try_from(self.config.user_name.clone())?;
let client = Client::new(self.config.homeserver_url.clone())?; let client = Client::new(self.config.homeserver_url.clone())?;
...@@ -177,44 +220,6 @@ impl Bot { ...@@ -177,44 +220,6 @@ impl Bot {
"state member" "state member"
); );
let on_msg_room_event = |ev: SyncMessageEvent<MessageEventContent>,
room: Room,
__info: Option<EncryptionInfo>| async {
let sender_id = ev.sender.clone();
return_if!(sender_id.as_str() == room.own_user_id().as_str(), ());
if let (
Room::Joined(joined),
MessageType::Text(TextMessageEventContent { ref body, .. }),
) = (room, ev.content.msgtype.clone())
{
if body.starts_with("%") {
if let Some(stripped) = body.strip_prefix("%") {
let args = stripped.split(' ').collect::<Vec<&str>>();
let mut res: String = format!("Command not found");
if let Some(pkg) = self
.packages
.lock()
.unwrap()
.iter()
.find(|x| x.has_command(&args))
{
res = pkg.handle(&joined, &sender_id, args);
}
let event = ev.into_full_event(joined.room_id().clone());
let msg = AnyMessageEventContent::RoomMessage(
MessageEventContent::text_reply_html(res.clone(), res, &event),
);
joined.send(msg, None).await.unwrap();
}
}
};
};
client.register_event_handler(on_msg_room_event).await;
client.register_event_handler(on_msg_room_reaction).await;
self.client = Some(client); self.client = Some(client);
return Ok(self); return Ok(self);
} }
...@@ -223,6 +228,9 @@ impl Bot { ...@@ -223,6 +228,9 @@ impl Bot {
match &self.client { match &self.client {
None => abort(), None => abort(),
Some(client) => { Some(client) => {
client.register_event_handler(on_msg_room_event).await;
client.register_event_handler(on_msg_room_reaction).await;
info!("Entering sync loop"); info!("Entering sync loop");
let token = client.sync_token().await.unwrap(); let token = client.sync_token().await.unwrap();
client.sync(SyncSettings::default().token(token)).await; client.sync(SyncSettings::default().token(token)).await;
...@@ -231,14 +239,13 @@ impl Bot { ...@@ -231,14 +239,13 @@ impl Bot {
} }
} }
pub fn add_package(&mut self, name: String, cmds: Vec<Cmd>) -> &mut Self { pub fn add_package(config: &Config, name: String, cmds: Vec<Cmd>) {
let pkg = match self.config.section(&name) { let pkg = match config.section(&name) {
Some(section) => CmdPackage::from_config(&section, cmds), Some(section) => CmdPackage::from_config(&section, cmds),
None => { None => {
abort(); abort();
} }
}; };
self.packages.lock().unwrap().push(pkg); GLOBAL_PKG.lock().unwrap().push(pkg);
self
} }
} }
...@@ -20,10 +20,7 @@ async fn main() -> matrix_sdk::Result<()> { ...@@ -20,10 +20,7 @@ async fn main() -> matrix_sdk::Result<()> {
Cmd::new_echo(format!("bot_name"), 0, |_x| format!("toto")), Cmd::new_echo(format!("bot_name"), 0, |_x| format!("toto")),
]; ];
Bot::new(env::args().last().unwrap()) let mut bot = Bot::new(env::args().last().unwrap());
.add_package(format!("basic"), basic_cmds) Bot::add_package(bot.get_configuration(), format!("basic"), basic_cmds);
.connect() bot.connect().await?.listen().await
.await?
.listen()
.await
} }
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter