Skip to main content

af_slack/chat/
message.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use super::Attachment;
8use af_core::prelude::*;
9
10/// A unique identifier for a message.
11#[derive(Debug, Deserialize)]
12pub struct MessageId {
13  /// The ID of the channel.
14  pub channel: String,
15  /// The timestamp of the message.
16  pub ts: String,
17}
18
19/// A chat message.
20#[derive(Debug, Serialize)]
21pub struct Message<'a> {
22  pub attachments: Vec<Attachment<'a>>,
23  pub text: Cow<'a, str>,
24}
25
26impl<'a> Message<'a> {
27  /// Creates a new, empty chat message.
28  pub const fn new() -> Self {
29    Self { attachments: Vec::new(), text: Cow::Borrowed("") }
30  }
31
32  /// Adds an attachment to the message.
33  pub fn add_attachment(&mut self, attachment: Attachment<'a>) -> &mut Self {
34    self.attachments.push(attachment);
35    self
36  }
37
38  /// Sets the text of the message.
39  pub fn set_text(&mut self, text: impl Into<Cow<'a, str>>) -> &mut Self {
40    self.text = text.into();
41    self
42  }
43
44  /// Adds an attachment to the message.
45  pub fn with_attachment(mut self, attachment: Attachment<'a>) -> Self {
46    self.attachments.push(attachment);
47    self
48  }
49
50  /// Sets the text of the message.
51  pub fn with_text(mut self, text: impl Into<Cow<'a, str>>) -> Self {
52    self.set_text(text);
53    self
54  }
55}
56
57impl<'a> Default for Message<'a> {
58  fn default() -> Self {
59    Self::new()
60  }
61}
62
63impl<'a, T> From<T> for Message<'a>
64where
65  Cow<'a, str>: From<T>,
66{
67  fn from(text: T) -> Message<'a> {
68    let mut msg = Message::new();
69
70    msg.set_text(text);
71    msg
72  }
73}
74
75impl<'a> From<Attachment<'a>> for Message<'a> {
76  fn from(attachment: Attachment<'a>) -> Self {
77    let mut message = Self::new();
78
79    message.attachments.push(attachment);
80    message
81  }
82}