joining rooms, receiving messages

This commit is contained in:
Thomas Lindner 2024-01-04 00:00:49 +01:00
commit d65307985c
4 changed files with 2902 additions and 0 deletions

1
.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/target

2828
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

10
Cargo.toml Normal file
View file

@ -0,0 +1,10 @@
[package]
name = "matrixbot"
version = "0.1.0"
edition = "2021"
[dependencies]
anyhow = "1"
matrix-sdk = "0.6"
tokio = { version = "1", features = ["full"] }
tracing-subscriber = "0.3"

63
src/main.rs Normal file
View file

@ -0,0 +1,63 @@
use matrix_sdk::{
config::SyncSettings,
room::Room,
ruma::{
events::room::member::StrippedRoomMemberEvent, events::room::message::SyncRoomMessageEvent,
user_id::OwnedUserId,
},
Client,
};
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt::init();
let userid: OwnedUserId = std::env::args()
.nth(1)
.ok_or("need userid")
.map_err(anyhow::Error::msg)?
.try_into()?;
let client = Client::builder()
.server_name(userid.server_name())
.build()
.await?;
// First we need to log in.
client
.login_username(
&userid,
&std::env::args()
.nth(2)
.ok_or("need password")
.map_err(anyhow::Error::msg)?,
)
.send()
.await?;
client.add_event_handler(|ev: SyncRoomMessageEvent| async move {
println!("Received a message {:?}", ev);
});
client.add_event_handler(
|ev: StrippedRoomMemberEvent, client: Client, room: Room| async move {
if ev.state_key != client.user_id().unwrap() {
return;
}
if let Room::Invited(room) = room {
tokio::spawn(async move {
println!("Autojoining {}", room.room_id());
while let Err(err) = room.accept_invitation().await {
eprintln!("Failed to join room {}: {:?}", room.room_id(), err);
sleep(Duration::from_secs(5)).await;
}
});
}
},
);
// Syncing is important to synchronize the client state with the server.
// This method will never return.
client.sync(SyncSettings::default()).await?;
Ok(())
}