2020-04-22 04:19:15 +00:00
|
|
|
use crate::commands::parse_command;
|
2020-08-26 21:09:50 +00:00
|
|
|
use dirs;
|
|
|
|
use matrix_sdk::{
|
|
|
|
self,
|
|
|
|
events::{
|
|
|
|
room::message::{MessageEventContent, NoticeMessageEventContent, TextMessageEventContent},
|
2020-08-27 00:05:19 +00:00
|
|
|
AnyMessageEventContent, SyncMessageEvent,
|
2020-08-26 21:09:50 +00:00
|
|
|
},
|
|
|
|
Client, ClientConfig, EventEmitter, JsonStore, SyncRoom, SyncSettings,
|
|
|
|
};
|
|
|
|
use matrix_sdk_common_macros::async_trait;
|
2020-04-19 22:07:33 +00:00
|
|
|
use serde::{self, Deserialize, Serialize};
|
2020-08-26 21:09:50 +00:00
|
|
|
use thiserror::Error;
|
|
|
|
use url::Url;
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//TODO move the config structs and read_config into their own file.
|
2020-04-18 23:09:55 +00:00
|
|
|
|
|
|
|
/// The "matrix" section of the config, which gives home server, login information, and etc.
|
2020-04-17 22:53:27 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct MatrixConfig {
|
2020-04-18 23:09:55 +00:00
|
|
|
/// Your homeserver of choice, as an FQDN without scheme or path
|
|
|
|
pub home_server: String,
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Username to login as. Only the localpart.
|
|
|
|
pub username: String,
|
|
|
|
|
|
|
|
/// Bot account password.
|
|
|
|
pub password: String,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Represents the toml config file for the dicebot.
|
2020-04-17 22:53:27 +00:00
|
|
|
#[derive(Serialize, Deserialize, Debug)]
|
|
|
|
pub struct Config {
|
2020-04-18 23:09:55 +00:00
|
|
|
pub matrix: MatrixConfig,
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// The DiceBot struct itself is the core of the program, essentially the entrypoint
|
|
|
|
/// to the bot.
|
2020-04-17 22:53:27 +00:00
|
|
|
pub struct DiceBot {
|
|
|
|
client: Client,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DiceBot {
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Create a new dicebot with the given Matrix client.
|
|
|
|
pub fn new(client: Client) -> Self {
|
|
|
|
DiceBot { client }
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
}
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// This event emitter listens for messages with dice rolling commands.
|
|
|
|
/// Originally adapted from the matrix-rust-sdk command bot example.
|
|
|
|
#[async_trait]
|
|
|
|
impl EventEmitter for DiceBot {
|
|
|
|
async fn on_room_message(&self, room: SyncRoom, event: &SyncMessageEvent<MessageEventContent>) {
|
|
|
|
if let SyncRoom::Joined(room) = room {
|
|
|
|
let (msg_body, sender_username) = if let SyncMessageEvent {
|
|
|
|
content: MessageEventContent::Text(TextMessageEventContent { body, .. }),
|
|
|
|
sender,
|
|
|
|
..
|
|
|
|
} = event
|
|
|
|
{
|
|
|
|
(
|
|
|
|
body.clone(),
|
|
|
|
format!("@{}:{}", sender.localpart(), sender.server_name()),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
(String::new(), String::new())
|
|
|
|
};
|
|
|
|
|
|
|
|
let (plain, html) = match parse_command(&msg_body) {
|
|
|
|
Ok(Some(command)) => {
|
|
|
|
let command = command.execute();
|
|
|
|
(command.plain().into(), command.html().into())
|
|
|
|
}
|
|
|
|
Ok(None) => return,
|
|
|
|
Err(e) => {
|
|
|
|
let message = format!("Error parsing command: {}", e);
|
|
|
|
let html_message = format!("<p><strong>{}</strong></p>", message);
|
|
|
|
(message, html_message)
|
|
|
|
}
|
|
|
|
};
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
let plain = format!("{}\n{}", sender_username, plain);
|
|
|
|
let html = format!("<p>{}</p>\n{}", sender_username, html);
|
2020-08-27 00:05:19 +00:00
|
|
|
let content = AnyMessageEventContent::RoomMessage(MessageEventContent::Notice(
|
|
|
|
NoticeMessageEventContent::html(plain, html),
|
|
|
|
));
|
2020-08-26 21:09:50 +00:00
|
|
|
|
|
|
|
//we clone here to hold the lock for as little time as possible.
|
|
|
|
let room_id = room.read().await.room_id.clone();
|
|
|
|
let result = self.client.room_send(&room_id, content, None).await;
|
|
|
|
|
|
|
|
match result {
|
|
|
|
Err(e) => println!("Error sending message: {}", e.to_string()),
|
|
|
|
Ok(_) => (),
|
2020-04-18 23:09:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
}
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
#[derive(Error, Debug)]
|
|
|
|
pub enum BotError {
|
|
|
|
/// Sync token couldn't be found.
|
|
|
|
#[error("the sync token could not be retrieved")]
|
|
|
|
SyncTokenRequired,
|
|
|
|
}
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
/// Run the matrix dice bot until program terminated, or a panic occurs.
|
|
|
|
/// Originally adapted from the matrix-rust-sdk command bot example.
|
|
|
|
pub async fn run_bot(config: MatrixConfig) -> Result<(), Box<dyn std::error::Error>> {
|
|
|
|
let homeserver_url = config.home_server;
|
|
|
|
let username = config.username;
|
|
|
|
let password = config.password;
|
2020-04-20 21:09:38 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
let mut cache_dir = dirs::cache_dir().expect("no cache directory found");
|
|
|
|
cache_dir.push("matrix-dicebot");
|
2020-04-17 22:53:27 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
//If the local json store has not been created yet, we need to do a single initial sync.
|
|
|
|
//It stores data under username's localpart.
|
|
|
|
let should_sync = {
|
|
|
|
let mut cache = cache_dir.clone();
|
|
|
|
cache.push(username.clone());
|
|
|
|
!cache.exists()
|
|
|
|
};
|
|
|
|
|
|
|
|
let store = JsonStore::open(&cache_dir)?;
|
|
|
|
let client_config = ClientConfig::new().state_store(Box::new(store));
|
|
|
|
|
|
|
|
let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
|
|
|
|
let mut client = Client::new_with_config(homeserver_url, client_config).unwrap();
|
2020-04-18 23:09:55 +00:00
|
|
|
|
2020-08-26 21:09:50 +00:00
|
|
|
client
|
|
|
|
.login(&username, &password, None, Some("matrix dice bot"))
|
|
|
|
.await?;
|
|
|
|
|
|
|
|
println!("Logged in as {}", username);
|
|
|
|
|
|
|
|
if should_sync {
|
|
|
|
println!("Performing initial sync");
|
|
|
|
client.sync(SyncSettings::default()).await?;
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|
2020-08-26 21:09:50 +00:00
|
|
|
|
|
|
|
//Attach event handler.
|
|
|
|
client
|
|
|
|
.add_event_emitter(Box::new(DiceBot::new(client.clone())))
|
|
|
|
.await;
|
|
|
|
|
|
|
|
let token = client
|
|
|
|
.sync_token()
|
|
|
|
.await
|
|
|
|
.ok_or(BotError::SyncTokenRequired)?;
|
|
|
|
let settings = SyncSettings::default().token(token);
|
|
|
|
|
|
|
|
//this keeps state from the server streaming in to the dice bot via the EventEmitter trait
|
|
|
|
println!("Listening for commands");
|
|
|
|
client.sync_forever(settings, |_| async {}).await;
|
|
|
|
|
|
|
|
Ok(())
|
2020-04-17 22:53:27 +00:00
|
|
|
}
|