2021-01-31 14:06:25 +00:00
|
|
|
use log::error;
|
2021-04-20 21:19:47 +00:00
|
|
|
use matrix_sdk::events::room::message::NoticeMessageEventContent;
|
2021-02-09 22:22:09 +00:00
|
|
|
use matrix_sdk::{
|
|
|
|
events::room::message::{InReplyTo, Relation},
|
2021-03-15 20:10:42 +00:00
|
|
|
events::room::message::{MessageEventContent, MessageType},
|
|
|
|
events::AnyMessageEventContent,
|
2021-02-09 22:22:09 +00:00
|
|
|
identifiers::EventId,
|
|
|
|
Error as MatrixError,
|
|
|
|
};
|
2021-01-29 22:35:07 +00:00
|
|
|
use matrix_sdk::{identifiers::RoomId, Client};
|
2020-11-22 21:30:24 +00:00
|
|
|
|
2021-01-31 14:06:25 +00:00
|
|
|
/// Extracts more detailed error messages out of a matrix SDK error.
|
|
|
|
fn extract_error_message(error: MatrixError) -> String {
|
2021-02-07 21:58:22 +00:00
|
|
|
use matrix_sdk::{Error::Http, HttpError};
|
2021-05-13 19:48:29 +00:00
|
|
|
if let Http(HttpError::Api(ruma_err)) = error {
|
2021-02-08 20:14:11 +00:00
|
|
|
ruma_err.to_string()
|
|
|
|
} else {
|
|
|
|
error.to_string()
|
2021-01-31 14:06:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-22 21:30:24 +00:00
|
|
|
/// Retrieve a list of users in a given room.
|
|
|
|
pub async fn get_users_in_room(client: &Client, room_id: &RoomId) -> Vec<String> {
|
2021-01-29 22:35:07 +00:00
|
|
|
if let Some(joined_room) = client.get_joined_room(room_id) {
|
2021-04-20 21:19:47 +00:00
|
|
|
let members = joined_room.joined_members().await.ok().unwrap_or_default();
|
2021-02-08 20:14:11 +00:00
|
|
|
|
2021-02-10 20:18:47 +00:00
|
|
|
members
|
|
|
|
.into_iter()
|
|
|
|
.map(|member| member.user_id().to_string())
|
|
|
|
.collect()
|
2020-11-22 21:30:24 +00:00
|
|
|
} else {
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
}
|
2021-01-31 14:06:25 +00:00
|
|
|
|
2021-02-09 22:22:09 +00:00
|
|
|
pub async fn send_message(
|
|
|
|
client: &Client,
|
|
|
|
room_id: &RoomId,
|
|
|
|
message: &str,
|
|
|
|
reply_to: Option<EventId>,
|
|
|
|
) {
|
2021-03-15 20:10:42 +00:00
|
|
|
let room = match client.get_joined_room(room_id) {
|
|
|
|
Some(room) => room,
|
|
|
|
_ => return,
|
|
|
|
};
|
|
|
|
|
2021-01-31 14:06:25 +00:00
|
|
|
let plain = html2text::from_read(message.as_bytes(), message.len());
|
2021-03-15 20:10:42 +00:00
|
|
|
let mut content = MessageEventContent::new(MessageType::Notice(
|
|
|
|
NoticeMessageEventContent::html(plain.trim(), message),
|
|
|
|
));
|
2021-02-09 22:22:09 +00:00
|
|
|
|
|
|
|
content.relates_to = reply_to.map(|event_id| Relation::Reply {
|
|
|
|
in_reply_to: InReplyTo { event_id },
|
|
|
|
});
|
|
|
|
|
2021-03-15 20:10:42 +00:00
|
|
|
let content = AnyMessageEventContent::RoomMessage(content);
|
|
|
|
|
|
|
|
let result = room.send(content, None).await;
|
2021-01-31 14:06:25 +00:00
|
|
|
|
|
|
|
if let Err(e) = result {
|
|
|
|
let message = extract_error_message(e);
|
|
|
|
error!("Error sending message: {}", message);
|
|
|
|
};
|
|
|
|
}
|