example_get_profiles/
main.rs

1use std::{env, process::exit};
2
3use matrix_sdk::{
4    ruma::{api::client::profile, OwnedMxcUri, UserId},
5    Client, Result as MatrixResult,
6};
7use url::Url;
8
9#[derive(Debug)]
10#[allow(dead_code)]
11struct UserProfile {
12    avatar_url: Option<OwnedMxcUri>,
13    displayname: Option<String>,
14}
15
16/// This function calls the GET profile endpoint
17/// Spec: <https://matrix.org/docs/spec/client_server/r0.6.1#get-matrix-client-r0-profile-userid>
18/// Ruma: <https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/r0/profile/get_profile/index.html>
19async fn get_profile(client: Client, mxid: &UserId) -> MatrixResult<UserProfile> {
20    // First construct the request you want to make
21    // See https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/index.html for all available Endpoints
22    let request = profile::get_profile::v3::Request::new(mxid.to_owned());
23
24    // Start the request using matrix_sdk::Client::send
25    let resp = client.send(request).await?;
26
27    // Use the response and construct a UserProfile struct.
28    // See https://docs.rs/ruma-client-api/0.9.0/ruma_client_api/r0/profile/get_profile/struct.Response.html
29    // for details on the Response for this Request
30    let user_profile = UserProfile { avatar_url: resp.avatar_url, displayname: resp.displayname };
31    Ok(user_profile)
32}
33
34async fn login(
35    homeserver_url: String,
36    username: &str,
37    password: &str,
38) -> matrix_sdk::Result<Client> {
39    let homeserver_url = Url::parse(&homeserver_url).expect("Couldn't parse the homeserver URL");
40    let client = Client::new(homeserver_url).await.unwrap();
41
42    client
43        .matrix_auth()
44        .login_username(username, password)
45        .initial_device_display_name("rust-sdk")
46        .await?;
47
48    Ok(client)
49}
50
51#[tokio::main]
52async fn main() -> anyhow::Result<()> {
53    tracing_subscriber::fmt::init();
54
55    let (homeserver_url, username, password) =
56        match (env::args().nth(1), env::args().nth(2), env::args().nth(3)) {
57            (Some(a), Some(b), Some(c)) => (a, b, c),
58            _ => {
59                eprintln!(
60                    "Usage: {} <homeserver_url> <mxid> <password>",
61                    env::args().next().unwrap()
62                );
63                exit(1)
64            }
65        };
66
67    let client = login(homeserver_url, &username, &password).await?;
68
69    let user_id = UserId::parse(username).expect("Couldn't parse the MXID");
70    let profile = get_profile(client, &user_id).await?;
71    println!("{profile:#?}");
72    Ok(())
73}