archive_bot/
post.rs

1use log::warn;
2
3use crate::ArchiveBot;
4use crate::types::*;
5use crate::error::SlackError;
6
7impl ArchiveBot {
8  /// Post a message to a channel.
9  pub async fn post_message(&self, channel_id: &str, message: &str) -> Result<SlackResponse, SlackError<reqwest::Error>> {
10    let mut params: UrlParams = vec![
11      ("channel", channel_id.to_string()),
12      ("text", message.to_string()),
13      ("mrkdwn", String::from("1")),
14    ];
15
16    match self.send("chat.postMessage", &mut params).await {
17      Ok(r) => Ok(r),
18      Err(e) => {
19        warn!("Unable to post message: {:}", e);
20        Err(e)
21      },
22    }
23  }
24
25  /// Make Archive Bot join a channel.
26  pub async fn join_channel(&self, channel_id: &str) -> Result<SlackResponse, SlackError<reqwest::Error>> {
27    let mut params: UrlParams = vec![
28      ("channel", channel_id.to_string()),
29    ];
30
31    match self.send("conversations.join", &mut params).await {
32      Ok(r) => Ok(r),
33      Err(e) => {
34        warn!("Unable to join channel: {:}", e);
35        Err(e)
36      },
37    }
38  }
39}
40
41#[cfg(test)]
42mod tests {
43  #[cfg(feature="unit_output")]
44  use std::env;
45  #[cfg(feature="unit_output")]
46  use log::{info, error};
47  #[cfg(feature="unit_output")]
48  use simplelog;
49
50  /// Create a test message and print it to stdout rather than posting to Slack.
51  #[tokio::test]
52  #[cfg(feature = "unit_output")]
53  async fn test_send_message() {
54    simplelog::TermLogger::init(simplelog::LevelFilter::Debug, simplelog::Config::default(), simplelog::TerminalMode::Mixed, simplelog::ColorChoice::Auto).unwrap();
55    let bot = crate::ArchiveBot::_from_env_debug();
56    let channel_id = env::var("SLACK_CHANNEL_TEST_ID").expect("Error: environment variable SLACK_CHANNEL_TEST_ID is not set.");
57    let message = "Testing, 1 2 3. :robot_face:";
58    match bot.post_message(&channel_id, message).await {
59      Ok(_) => info!("Message sent."),
60      Err(e) => error!("Error: {}", e),
61    }
62  }
63}