mx-sanebot: split out some request/response interface

This commit is contained in:
Colin 2023-04-25 07:44:49 +00:00
parent 5d0630cad4
commit b282e5beb2
2 changed files with 71 additions and 11 deletions

View File

@ -1,4 +1,7 @@
mod msg_handler;
use std::env;
use matrix_sdk::{
config::SyncSettings,
room::Room,
@ -10,26 +13,35 @@ use matrix_sdk::{
};
use tokio::time::{sleep, Duration};
use msg_handler::MessageHandler;
async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
println!("received event");
if let Room::Joined(room) = room {
let text_content = match event.content.msgtype {
MessageType::Text(t) => t,
_ => return,
_ => return, // not of interest
};
if text_content.body.contains("!ping") {
let content = RoomMessageEventContent::text_plain("pong");
let sender = event.sender;
let msg = text_content.body;
println!("message from {sender}: {msg}\n");
println!("sending");
// send our message to the room we found the "!ping" command in
// the last parameter is an optional transaction id which we don't
// care about.
room.send(content, None).await.unwrap();
println!("message sent");
if sender.as_str() == "@sanebot:uninsane.org" {
return; // don't respond to myself!
}
let resp = MessageHandler.on_msg(&msg);
println!("response: {}", resp);
let resp_content = RoomMessageEventContent::text_plain(&resp);
// send our message to the room we found the "!ping" command in
// the last parameter is an optional transaction id which we don't
// care about.
room.send(resp_content, None).await.unwrap();
println!("response sent");
}
}

View File

@ -0,0 +1,48 @@
use std::fmt;
pub struct MessageHandler;
impl MessageHandler {
/// parse any message directed to me, and return text to present to the user who messaged me.
/// the message passed here may or may not be a "valid" request.
/// if invalid, expect an error message or help message, still meant for the user.
pub fn on_msg(&self, msg: &str) -> String {
let req = self.parse_msg(msg).unwrap_or(Request::Help);
let resp = req.evaluate();
resp.to_string()
}
fn parse_msg(&self, msg: &str) -> Result<Request, ()> {
let msg = msg.trim();
if msg == "!help" {
Ok(Request::Help)
} else {
Err(())
}
}
}
enum Request {
Help,
}
impl Request {
fn evaluate(self) -> Response {
match self {
Request::Help => Response::About,
}
}
}
enum Response {
About,
}
impl fmt::Display for Response {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "commands:\n")?;
write!(f, " !help => show this message\n")?;
Ok(())
}
}