summaryrefslogtreecommitdiff
path: root/src/command_handler.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/command_handler.rs')
-rw-r--r--src/command_handler.rs85
1 files changed, 85 insertions, 0 deletions
diff --git a/src/command_handler.rs b/src/command_handler.rs
new file mode 100644
index 0000000..71aba3f
--- /dev/null
+++ b/src/command_handler.rs
@@ -0,0 +1,85 @@
+//! Module to handle commands sent directly to the bot, as opposed to something
+//! that scans the messages for Žižek-trigger-words.
+
+/// The leading command the bot is looking for before any internal command
+pub const COMMAND_PREFIX: &'static str = "/zizek ";
+
+const ZIZEK_ADD_QUOTE_NOTICE: &'static str = "I think I'll add that to my repertoire.";
+const ZIZEK_KNOWN_QUOTE_NOTICE: &'static str = "Hey, I know that one, that's a good one!";
+const ZIZEK_EMPTY_NOTICE: &'static str =
+ "You know, it's quite funny to me. The moment you call I've ran out of material.";
+const CMD_ADD: &'static str = "add";
+
+use std::sync::{Arc, Mutex};
+
+use matrix_bot_api::handlers::{extract_command, HandleResult, MessageHandler};
+use matrix_bot_api::{ActiveBot, Message, MessageType};
+
+use crate::zizek_db::ZizekDb;
+
+/// Command handler struct that can be passed to the matrix bot as a handler
+pub struct CommandHandler
+{
+ zizek_db: Arc<Mutex<ZizekDb>>,
+}
+
+impl CommandHandler
+{
+ /// Create a new command handler with access to the zizek quote database
+ pub fn new(zizek_db: Arc<Mutex<ZizekDb>>) -> Self { Self { zizek_db } }
+
+ fn handle_zizek(&self, bot: &ActiveBot, message: &Message)
+ {
+ let zizek_lock = self.zizek_db.lock().unwrap();
+ let quote = zizek_lock.random_quote().map_or(ZIZEK_EMPTY_NOTICE, |s| &s);
+
+ bot.send_message(quote, &message.room, MessageType::TextMessage);
+ }
+
+ fn handle_add_quote(&mut self, bot: &ActiveBot, message: &Message)
+ {
+ let mut zizek_lock = self.zizek_db.lock().unwrap();
+
+ let quote = &message.body[COMMAND_PREFIX.len() + CMD_ADD.len() + 1..];
+ if zizek_lock.add_quote(quote) {
+ bot.send_message(
+ ZIZEK_ADD_QUOTE_NOTICE,
+ &message.room,
+ MessageType::TextMessage,
+ );
+ }
+ else {
+ bot.send_message(
+ ZIZEK_KNOWN_QUOTE_NOTICE,
+ &message.room,
+ MessageType::TextMessage,
+ );
+ }
+ }
+}
+
+impl MessageHandler for CommandHandler
+{
+ fn handle_message(&mut self, bot: &ActiveBot, message: &Message) -> HandleResult
+ {
+ if let Some(command) = extract_command(&message.body, COMMAND_PREFIX) {
+ match command {
+ "" => {
+ self.handle_zizek(bot, message);
+ HandleResult::StopHandling
+ },
+ CMD_ADD => {
+ self.handle_add_quote(bot, message);
+ HandleResult::StopHandling
+ },
+ _ => {
+ println!("Žižek cannot be handled.");
+ HandleResult::ContinueHandling
+ },
+ }
+ }
+ else {
+ HandleResult::ContinueHandling
+ }
+ }
+}