misskey_util/builder/
messaging.rs

1use crate::Error;
2
3use misskey_api::model::{
4    drive::DriveFile, messaging::MessagingMessage, user::User, user_group::UserGroup,
5};
6use misskey_api::{endpoint, EntityRef};
7use misskey_core::Client;
8
9/// Builder for the [`build_message`][`crate::ClientExt::build_message`] method.
10pub struct MessagingMessageBuilder<C> {
11    client: C,
12    request: endpoint::messaging::messages::create::Request,
13}
14
15impl<C> MessagingMessageBuilder<C> {
16    /// Creates a builder with the client.
17    pub fn new(client: C) -> Self {
18        let request = endpoint::messaging::messages::create::Request {
19            text: None,
20            user_id: None,
21            group_id: None,
22            file_id: None,
23        };
24        MessagingMessageBuilder { client, request }
25    }
26
27    /// Gets the request object for reuse.
28    pub fn as_request(&self) -> &endpoint::messaging::messages::create::Request {
29        &self.request
30    }
31
32    /// Sets the text content of the message.
33    pub fn text(&mut self, text: impl Into<String>) -> &mut Self {
34        self.request.text.replace(text.into());
35        self
36    }
37
38    /// Specifies the recipient user.
39    ///
40    /// Note that user and group cannot be specified as the recipient at the same time.
41    /// Therefore, even if [`group`][`MessagingMessageBuilder::group`] is used before this method call,
42    /// it will be overwritten and the message is only sent to the user specified in this call.
43    pub fn user(&mut self, user: impl EntityRef<User>) -> &mut Self {
44        self.request.user_id.replace(user.entity_ref());
45        self.request.group_id.take();
46        self
47    }
48
49    /// Specifies the recipient user group.
50    ///
51    /// Note that user and group cannot be specified as the recipient at the same time.
52    /// Therefore, even if [`user`][`MessagingMessageBuilder::user`] is used before this method call,
53    /// it will be overwritten and the message is only sent to the user group specified in this call.
54    pub fn group(&mut self, group: impl EntityRef<UserGroup>) -> &mut Self {
55        self.request.group_id.replace(group.entity_ref());
56        self.request.user_id.take();
57        self
58    }
59
60    /// Sets the file content of the message.
61    pub fn file(&mut self, file: impl EntityRef<DriveFile>) -> &mut Self {
62        self.request.file_id.replace(file.entity_ref());
63        self
64    }
65}
66
67impl<C: Client> MessagingMessageBuilder<C> {
68    /// Creates the message.
69    pub async fn create(&self) -> Result<MessagingMessage, Error<C::Error>> {
70        let message = self
71            .client
72            .request(&self.request)
73            .await
74            .map_err(Error::Client)?
75            .into_result()?;
76        Ok(message)
77    }
78}