example_image_bot/
main.rs1use std::{env, fs, process::exit};
2
3use matrix_sdk::{
4 attachment::AttachmentConfig,
5 config::SyncSettings,
6 ruma::events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
7 Client, Room, RoomState,
8};
9use url::Url;
10
11async fn on_room_message(event: OriginalSyncRoomMessageEvent, room: Room, image: Vec<u8>) {
12 if room.state() != RoomState::Joined {
13 return;
14 }
15 let MessageType::Text(text_content) = event.content.msgtype else { return };
16
17 if text_content.body.contains("!image") {
18 println!("sending image");
19 room.send_attachment(
20 "cat.jpg",
21 &mime::IMAGE_JPEG,
22 image,
23 AttachmentConfig::new().caption(Some("my pretty cat".to_owned())),
24 )
25 .await
26 .unwrap();
27
28 println!("message sent");
29 }
30}
31
32async fn login_and_sync(
33 homeserver_url: String,
34 username: String,
35 password: String,
36 image: Vec<u8>,
37) -> matrix_sdk::Result<()> {
38 let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
39 let client = Client::new(homeserver_url).await.unwrap();
40
41 client
42 .matrix_auth()
43 .login_username(&username, &password)
44 .initial_device_display_name("command bot")
45 .await?;
46
47 let response = client.sync_once(SyncSettings::default()).await.unwrap();
48
49 client.add_event_handler(move |ev, room| on_room_message(ev, room, image));
50
51 let settings = SyncSettings::default().token(response.next_batch);
52 client.sync(settings).await?;
53
54 Ok(())
55}
56
57#[tokio::main]
58async fn main() -> anyhow::Result<()> {
59 tracing_subscriber::fmt::init();
60 let (homeserver_url, username, password, image_path) =
61 match (env::args().nth(1), env::args().nth(2), env::args().nth(3), env::args().nth(4)) {
62 (Some(a), Some(b), Some(c), Some(d)) => (a, b, c, d),
63 _ => {
64 eprintln!(
65 "Usage: {} <homeserver_url> <username> <password> <image>",
66 env::args().next().unwrap()
67 );
68 exit(1)
69 }
70 };
71
72 println!("helloooo {homeserver_url} {username} {password} {image_path:#?}");
73 let image = fs::read(&image_path).expect("Can't open image file.");
74
75 login_and_sync(homeserver_url, username, password, image).await?;
76 Ok(())
77}