2022-12-10 / @syui

matrix , rust

matrixのclientを作ってみた

matrix-rust-sdk

どんな感じで書けばいいのかexampleを載せておきます。そのままでは動きませんが。

#[allow(unused_mut)]
let mut client_builder = Client::builder().homeserver_url(homeserver_url);
#[cfg(feature = "sled")]
{
    let home = dirs::home_dir().expect("no home directory found").join("sdk");
    client_builder = client_builder.sled_store(home, None)?;
}
#[cfg(feature = "indexeddb")]
{
    client_builder = client_builder.indexeddb_store("sdk", None).await?;
}
let client = client_builder.build().await?;

// login
client
    .login_username(username, password)
    .initial_device_display_name("sdk")
    .send()
    .await?;

// sync
client.sync_once(SyncSettings::default()).await.unwrap().next_batch;

let sync_token = client.sync_once(SyncSettings::default()).await.unwrap().next_batch;
let settings = SyncSettings::default().token(sync_token);
client.sync(settings).await?;
client.sync(SyncSettings::default()).await?;
let alias = "#example:matrix.org";
let id = "!example:matrix.org";
let message = "test";

// room_id
let room_id = <&RoomId>::try_from(id).unwrap();

// room_alias
let room_alias = <&RoomAliasId>::try_from(alias).unwrap();
let room = client.resolve_room_alias(&room_alias).await?;
let room_id = room.room_id;

if let Some(room) = client.get_joined_room(&room_id) {
    // text
    client.join_room_by_id(&room_id).await?;
    let content = RoomMessageEventContent::text_plain(&message);
    room.send(content, None).await?;

    // html
    let o = "<code>test</code>";
    let content = RoomMessageEventContent::text_html(&message, &o);
    room.send(content, None).await?;
}
async fn timeline(event: OriginalSyncRoomMessageEvent, room: Room) {
    let Room::Joined(room) = room else { return };
    let room_id = room.room_id();
    let u = event.sender;
    let body = event.content.body();
    println!("{} {} {}", room_id, u, body);
}

client.add_event_handler(timeline);
async fn bot(event: OriginalSyncRoomMessageEvent, room: Room) {
    let Room::Joined(room) = room else { return };
    let MessageType::Text(text_content) = event.content.msgtype else { return };
    if text_content.body.contains("!party") {
        let content = RoomMessageEventContent::text_plain("test");
        room.send(content, None).await.unwrap();
    }
}

client.add_event_handler(bot);