matrix-rust-sdk/crates/matrix-sdk-appservice/examples/appservice_autojoin.rs

60 lines
1.8 KiB
Rust
Raw Permalink Normal View History

2021-06-04 12:16:24 +00:00
use std::{convert::TryFrom, env};
use matrix_sdk_appservice::{
2021-06-08 09:18:56 +00:00
matrix_sdk::{
2021-06-04 12:16:24 +00:00
room::Room,
ruma::{
events::{
room::member::{MemberEventContent, MembershipState},
SyncStateEvent,
},
UserId,
},
2021-06-04 12:16:24 +00:00
},
2021-06-22 09:36:33 +00:00
AppService, AppServiceRegistration, Result,
2021-06-04 12:16:24 +00:00
};
2021-06-22 09:36:33 +00:00
use tracing::trace;
2021-06-04 12:16:24 +00:00
2021-06-22 09:36:33 +00:00
pub async fn handle_room_member(
appservice: AppService,
2021-06-22 09:36:33 +00:00
room: Room,
event: SyncStateEvent<MemberEventContent>,
) -> Result<()> {
if !appservice.user_id_is_in_namespace(&event.state_key)? {
trace!("not an appservice user: {}", event.state_key);
} else if let MembershipState::Invite = event.content.membership {
let user_id = UserId::try_from(event.state_key.as_str())?;
appservice.register_virtual_user(user_id.localpart()).await?;
let client = appservice.virtual_user_client(user_id.localpart()).await?;
client.join_room_by_id(room.room_id()).await?;
2021-06-04 12:16:24 +00:00
}
2021-06-22 09:36:33 +00:00
Ok(())
2021-06-04 12:16:24 +00:00
}
#[tokio::main]
pub async fn main() -> Result<(), Box<dyn std::error::Error>> {
env::set_var("RUST_LOG", "matrix_sdk=debug,matrix_sdk_appservice=debug");
tracing_subscriber::fmt::init();
let homeserver_url = "http://localhost:8008";
let server_name = "localhost";
let registration = AppServiceRegistration::try_from_yaml_file("./tests/registration.yaml")?;
2021-06-04 12:16:24 +00:00
let mut appservice = AppService::new(homeserver_url, server_name, registration).await?;
2021-06-22 09:36:33 +00:00
appservice
.register_event_handler({
let appservice = appservice.clone();
move |event: SyncStateEvent<MemberEventContent>, room: Room| {
handle_room_member(appservice.clone(), room, event)
}
})
.await?;
2021-06-04 12:16:24 +00:00
let (host, port) = appservice.registration().get_host_and_port()?;
appservice.run(host, port).await?;
Ok(())
}