1use std::{env, process::exit};
23use matrix_sdk::{
4 config::SyncSettings,
5 ruma::events::room::message::{
6 MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent,
7 },
8 Client, Room, RoomState,
9};
1011async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
12if room.state() != RoomState::Joined {
13return;
14 }
15let MessageType::Text(text_content) = event.content.msgtype else {
16return;
17 };
1819if text_content.body.contains("!party") {
20let content = RoomMessageEventContent::text_plain("🎉🎊🥳 let's PARTY!! 🥳🎊🎉");
2122println!("sending");
2324// send our message to the room we found the "!party" command in
25room.send(content).await.unwrap();
2627println!("message sent");
28 }
29}
3031async fn login_and_sync(
32 homeserver_url: String,
33 username: String,
34 password: String,
35) -> anyhow::Result<()> {
36// Note that when encryption is enabled, you should use a persistent store to be
37 // able to restore the session with a working encryption setup.
38 // See the `persist_session` example.
39let client = Client::builder().homeserver_url(homeserver_url).build().await.unwrap();
40 client
41 .matrix_auth()
42 .login_username(&username, &password)
43 .initial_device_display_name("command bot")
44 .await?;
4546println!("logged in as {username}");
4748// An initial sync to set up state and so our bot doesn't respond to old
49 // messages.
50let response = client.sync_once(SyncSettings::default()).await.unwrap();
51// add our CommandBot to be notified of incoming messages, we do this after the
52 // initial sync to avoid responding to messages before the bot was running.
53client.add_event_handler(on_room_message);
5455// since we called `sync_once` before we entered our sync loop we must pass
56 // that sync token to `sync`
57let settings = SyncSettings::default().token(response.next_batch);
58// this keeps state from the server streaming in to CommandBot via the
59 // EventHandler trait
60client.sync(settings).await?;
6162Ok(())
63}
6465#[tokio::main]
66async fn main() -> anyhow::Result<()> {
67 tracing_subscriber::fmt::init();
6869let (homeserver_url, username, password) =
70match (env::args().nth(1), env::args().nth(2), env::args().nth(3)) {
71 (Some(a), Some(b), Some(c)) => (a, b, c),
72_ => {
73eprintln!(
74"Usage: {} <homeserver_url> <username> <password>",
75 env::args().next().unwrap()
76 );
77 exit(1)
78 }
79 };
8081 login_and_sync(homeserver_url, username, password).await?;
82Ok(())
83}