example_command_bot/
main.rs

1use std::{env, process::exit};
2
3use matrix_sdk::{
4    config::SyncSettings,
5    ruma::events::room::message::{
6        MessageType, OriginalSyncRoomMessageEvent, RoomMessageEventContent,
7    },
8    Client, Room, RoomState,
9};
10
11async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room) {
12    if room.state() != RoomState::Joined {
13        return;
14    }
15    let MessageType::Text(text_content) = event.content.msgtype else {
16        return;
17    };
18
19    if text_content.body.contains("!party") {
20        let content = RoomMessageEventContent::text_plain("🎉🎊🥳 let's PARTY!! 🥳🎊🎉");
21
22        println!("sending");
23
24        // send our message to the room we found the "!party" command in
25        room.send(content).await.unwrap();
26
27        println!("message sent");
28    }
29}
30
31async 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.
39    let 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?;
45
46    println!("logged in as {username}");
47
48    // An initial sync to set up state and so our bot doesn't respond to old
49    // messages.
50    let 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.
53    client.add_event_handler(on_room_message);
54
55    // since we called `sync_once` before we entered our sync loop we must pass
56    // that sync token to `sync`
57    let settings = SyncSettings::default().token(response.next_batch);
58    // this keeps state from the server streaming in to CommandBot via the
59    // EventHandler trait
60    client.sync(settings).await?;
61
62    Ok(())
63}
64
65#[tokio::main]
66async fn main() -> anyhow::Result<()> {
67    tracing_subscriber::fmt::init();
68
69    let (homeserver_url, username, password) =
70        match (env::args().nth(1), env::args().nth(2), env::args().nth(3)) {
71            (Some(a), Some(b), Some(c)) => (a, b, c),
72            _ => {
73                eprintln!(
74                    "Usage: {} <homeserver_url> <username> <password>",
75                    env::args().next().unwrap()
76                );
77                exit(1)
78            }
79        };
80
81    login_and_sync(homeserver_url, username, password).await?;
82    Ok(())
83}