/ src / matrix / mod.rs
mod.rs
 1  use std::{path::Path, sync::Arc};
 2  
 3  use anyhow::Context as _;
 4  use matrix_sdk::{Client, config::SyncSettings, ruma::api::client::filter::FilterDefinition};
 5  
 6  use crate::context::Context;
 7  
 8  mod commands;
 9  mod event_handlers;
10  pub mod utils;
11  
12  pub async fn create_client(homeserver_url: &str, store_path: &Path) -> anyhow::Result<Client> {
13      Client::builder()
14          .homeserver_url(homeserver_url)
15          .sqlite_store(store_path, None)
16          .build()
17          .await
18          .context("Failed to create client")
19  }
20  
21  pub struct Bot {
22      client: Client,
23      sync_settings: SyncSettings,
24  }
25  
26  impl Bot {
27      pub async fn setup(client: Client) -> anyhow::Result<Self> {
28          let mut filter = FilterDefinition::ignore_all();
29          filter.room.timeline.not_senders = vec![client.user_id().unwrap().into()];
30          filter.room.timeline.types = Some(
31              [
32                  "m.room.message",
33                  "m.room.encrypted",
34                  "m.room.encryption",
35                  "m.room.member",
36              ]
37              .into_iter()
38              .map(Into::into)
39              .collect(),
40          );
41          filter.room.rooms = None;
42  
43          let sync_settings = SyncSettings::new().filter(filter.into());
44          let sync_response = client.sync_once(sync_settings.clone()).await?;
45          let sync_settings = sync_settings.token(sync_response.next_batch);
46  
47          Ok(Self {
48              client,
49              sync_settings,
50          })
51      }
52  
53      pub async fn start(self, context: Arc<Context>) -> anyhow::Result<()> {
54          event_handlers::add_event_handlers(&self.client, context);
55  
56          self.client.sync(self.sync_settings).await?;
57  
58          Ok(())
59      }
60  }