1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use notifier::INotifier;
use slack_hook::{Slack, PayloadBuilder, AttachmentBuilder};
use notifier_error::NotifierError;
use notification_level::NotificationLevel;

pub struct SlackNotifier {
    slack: Slack
}

impl SlackNotifier {
    pub fn new(webhook_url: &String) -> Result<SlackNotifier, NotifierError> {
        let s = SlackNotifier {
            slack: Slack::new(webhook_url.as_str())?
        };
        Ok(s)
    }

    pub fn get_color(notification_level: &NotificationLevel) -> &'static str {
        match notification_level {
            NotificationLevel::None => "#d6d6d6",
            NotificationLevel::Good => "good",
            NotificationLevel::Warning => "warning",
            NotificationLevel::Danger => "danger"
        }
    }

    pub fn notify(webhook_url: &String, message: &String, notification_level: NotificationLevel) {        
        let slack = match Slack::new(webhook_url.as_str()) {
            Ok(s) => s,
            _ => return
        };

        let attachments = match AttachmentBuilder::new(message.as_str())
            .color(SlackNotifier::get_color(&notification_level))
            .build() {
                Ok(a) => vec![a],
                _ => return
        };

        let p = match PayloadBuilder::new()
            .attachments(attachments)
            .link_names(true)
            .build() {
                Ok(p) => p,
                _ => return
        };

        match slack.send(&p) {
            Err(e) => println!("notifier-rs error: {:?}", e),
            _ => {}
        }
    }
}

impl INotifier for SlackNotifier {
    fn notify(&self, message: &String, notification_level: &NotificationLevel) {
        let attachments = match AttachmentBuilder::new(message.as_str())
            .color(SlackNotifier::get_color(&notification_level))
            .build() {
                Ok(a) => vec![a],
                _ => return
        };

        let p = match PayloadBuilder::new()
            .attachments(attachments)
            .link_names(true)
            .build() {
                Ok(p) => p,
                _ => return
        };

        match self.slack.send(&p) {
            Err(e) => println!("notifier-rs error: {:?}", e),
            _ => {}
        }
    }
}