matrix-bot/src/main.rs

281 lines
7.8 KiB
Rust

#![warn(clippy::nursery, clippy::pedantic)]
use std::fmt::Display;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
use clap::Parser;
use enum_iterator::IntoEnumIterator;
use matrix_sdk::room::{Joined, Room};
use matrix_sdk::ruma::events::room::member::MemberEventContent;
use matrix_sdk::ruma::events::room::message::{
MessageEventContent, MessageType, TextMessageEventContent,
};
use matrix_sdk::ruma::events::{StrippedStateEvent, SyncMessageEvent};
use matrix_sdk::ruma::UserId;
use matrix_sdk::{Client, ClientConfig, Result, Session, SyncSettings};
use serde::{Deserialize, Serialize};
use tracing::{error, info};
#[derive(Parser)]
struct Args {
#[clap(subcommand)]
subcommand: Command,
}
#[derive(Parser)]
enum Command {
Login {
user_id: UserId,
password: String,
},
Run {
#[clap(default_value = "config.toml")]
config_path: PathBuf,
#[clap(default_value = "data")]
store_path: PathBuf,
},
}
#[derive(Serialize, Deserialize)]
struct TomlConfig {
session: Session,
}
#[tokio::main]
async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse();
match args.subcommand {
Command::Login { user_id, password } => handle_login(user_id, &password).await,
Command::Run {
config_path,
store_path,
} => handle_run(config_path, store_path).await,
}
}
async fn handle_login(user_id: UserId, password: &str) -> Result<()> {
let client = Client::new_from_user_id(user_id.clone()).await?;
let resp = client
.login(user_id.localpart(), password, None, None)
.await?;
info!("Config generated. Please store this somewhere (like config.toml)!");
println!(
"\n\n{}",
toml::to_string_pretty(&TomlConfig {
session: Session {
access_token: resp.access_token,
device_id: resp.device_id,
user_id,
}
})
.unwrap()
);
Ok(())
}
async fn handle_run(config_path: PathBuf, store_path: PathBuf) -> Result<()> {
let data = std::fs::read_to_string(config_path)?;
let config: TomlConfig = toml::from_str(&data).unwrap();
let client_config = ClientConfig::default().store_path(store_path);
let client =
Client::new_from_user_id_with_config(config.session.user_id.clone(), client_config).await?;
client.restore_login(config.session.clone()).await?;
info!(user = %config.session.user_id, device_id = %config.session.device_id, "Logged in");
let sync_settings = SyncSettings::default();
// Sync once before registering events to not double-send events on boot.
client.sync_once(sync_settings.clone()).await?;
client
.register_event_handler(auto_join)
.await
.register_event_handler(on_room_message)
.await;
// Syncing is important to synchronize the client state with the server.
// This method will never return.
client.sync(sync_settings).await;
Ok(())
}
async fn auto_join(
room_member: StrippedStateEvent<MemberEventContent>,
client: Client,
room: Room,
) -> Result<()> {
if room_member.state_key != client.user_id().await.unwrap() {
return Ok(());
}
if let Room::Invited(room) = room {
info!("Autojoining room {}", room.room_id());
let mut delay = 2;
while let Err(err) = room.accept_invitation().await {
// retry autojoin due to synapse sending invites, before the
// invited user can join for more information see
// https://github.com/matrix-org/synapse/issues/4345
error!(
room_id = ?room.room_id(),
?err,
"Failed to join room, retrying in {delay}s",
);
tokio::time::sleep(Duration::from_secs(delay)).await;
delay *= 2;
if delay > 3600 {
error!(
room_id = ?room.room_id(),
?err,
"Failed to join room. Giving up.",
);
break;
}
}
info!(room_id = ?room.room_id(), "Successfully joined room.");
}
Ok(())
}
async fn on_room_message(
event: SyncMessageEvent<MessageEventContent>,
room: Room,
client: Client,
) -> Result<()> {
// Ignore messages sent from self.
if client.user_id().await.as_ref() == Some(&event.sender) {
return Ok(());
}
if let Room::Joined(room) = room {
parse_message(event, room).await?;
}
Ok(())
}
async fn parse_message(event: SyncMessageEvent<MessageEventContent>, room: Joined) -> Result<()> {
let message = match &event.content.msgtype {
MessageType::Text(TextMessageEventContent { body, .. }) => body.clone(),
_ => return Ok(()),
};
if let Some(message) = message.strip_prefix('!') {
let (command, args) = message.split_once(' ').unwrap_or((message, ""));
match BotCommand::from_str(command).ok() {
Some(BotCommand::Source) => source(room).await?,
Some(BotCommand::Uwu) => uwuify(room, args).await?,
Some(BotCommand::Ping) => ping(room).await?,
Some(BotCommand::Help) => help(room).await?,
_ => unsupported_command(event, room, command).await?,
}
}
Ok(())
}
#[derive(enum_iterator::IntoEnumIterator)]
enum BotCommand {
Help,
Source,
Uwu,
Ping,
}
impl BotCommand {
const fn help_text(&self) -> &'static str {
match self {
Self::Source => "Links to the source code for this bot.",
Self::Uwu => "Uwuifies your message.",
Self::Ping => "Pong!",
Self::Help => "Prints this help.",
}
}
}
impl FromStr for BotCommand {
type Err = ();
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"source" => Ok(Self::Source),
"uwu" => Ok(Self::Uwu),
"ping" => Ok(Self::Ping),
"help" => Ok(Self::Help),
_ => Err(()),
}
}
}
impl Display for BotCommand {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
BotCommand::Source => write!(f, "source"),
BotCommand::Uwu => write!(f, "uwu"),
BotCommand::Ping => write!(f, "ping"),
BotCommand::Help => write!(f, "help"),
}
}
}
async fn source(room: Joined) -> Result<()> {
let content = MessageEventContent::text_plain("https://git.eddie.sh/edward/matrix-bot");
room.send(content, None).await?;
Ok(())
}
async fn uwuify(room: Joined, message: &str) -> Result<()> {
let message = if message.is_empty() {
"uwu".to_owned()
} else {
uwuifier::uwuify_str_sse(message)
};
let content = MessageEventContent::text_plain(message);
room.send(content, None).await?;
Ok(())
}
async fn ping(room: Joined) -> Result<()> {
let content = MessageEventContent::text_plain("Pong!");
room.send(content, None).await?;
Ok(())
}
async fn help(room: Joined) -> Result<()> {
let mut msg = "List of commands:\n\n".to_owned();
for command in BotCommand::into_enum_iter() {
msg.push_str(&command.to_string());
msg.push_str(" - ");
msg.push_str(command.help_text());
msg.push_str("\n");
}
let content = MessageEventContent::notice_plain(msg);
room.send(content, None).await?;
Ok(())
}
async fn unsupported_command(
original_event: SyncMessageEvent<MessageEventContent>,
room: Joined,
command: &str,
) -> Result<()> {
let resp = original_event.into_full_event(room.room_id().clone());
let content =
MessageEventContent::notice_reply_plain(format!("Unknown command `{command}`"), &resp);
room.send(content, None).await?;
Ok(())
}