slack_message.py 3.54 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
import json

from urllib import request

SLACK_MESSAGE_COLOR_GREEN = "good"
SLACK_MESSAGE_COLOR_RED = "danger"
SLACK_WEB_HOOK_BASE_URL = "https://hooks.slack.com/services/"

SUCCEEDED = "Succeeded"
FAILED = "Failed"


class SlackMessenger:
xaingling's avatar
xaingling committed
14
15
16
    SUCCEEDED = SUCCEEDED
    FAILED = FAILED

17
18
19
20
21
22
23
24
25
26
27
28
29
30
    def __init__(self, slack_token=None, project_name=None, channel=None):
        self.slack_token = slack_token
        self.project_name = project_name
        self.channel = channel

    def _set_up_checking(self):
        if any([not self.channel, not self.slack_token, not self.project_name]):
            raise ValueError("Has to set up the slack message before sending message")

    def set_up(self, slack_token, project_name, channel):
        self.slack_token = slack_token
        self.project_name = project_name
        self.channel = channel

31
    def send_success_message(self, job_name, detail, title=None, text=None):
32
        self._set_up_checking()
33
        self.send_message(job_name, detail, title=title, text=text)
34

35
    def send_fail_message(self, job_name, detail, title=None, text=None):
36
        self._set_up_checking()
37
        self.send_message(job_name, detail, status=FAILED, title=title, text=text)
38

xaingling's avatar
xaingling committed
39
40
    def send_message(self, job_name, detail, status=SUCCEEDED, title=None, text=None):
        sending_dict = self.text_dict_maker(job_name, status, detail, title=title, text=text)
41
42
43
44
45
46
47
48
49
50
51
52
53
        self._sending_message(sending_dict)

    def _sending_message(self, text_dict):
        post = text_dict
        try:
            json_data = json.dumps(post)
            req = request.Request(SLACK_WEB_HOOK_BASE_URL + self.slack_token,
                                  data=json_data.encode('ascii'),
                                  headers={'Content-Type': 'application/json'})
            resp = request.urlopen(req)
        except Exception as em:
            print("EXCEPTION: " + str(em))

xaingling's avatar
xaingling committed
54
    def text_dict_maker(self, job_name, status, detail, title=None, text=None):
55
56
        if status == SUCCEEDED:
            color = SLACK_MESSAGE_COLOR_GREEN
xaingling's avatar
xaingling committed
57
        elif status == FAILED:
58
            color = SLACK_MESSAGE_COLOR_RED
xaingling's avatar
xaingling committed
59
        else:
xaingling's avatar
xaingling committed
60
            msg = "status code should be either {} or {}".format(SUCCEEDED, FAILED)
xaingling's avatar
xaingling committed
61
            raise ValueError(msg)
62
63
64
65
66

        sending_dict = {
            "channel": self.channel,
            "attachments": [
                {
xaingling's avatar
xaingling committed
67
                    "fallback": "This message was sent from {} project".format(self.project_name),
68
                    "color": color,
69
                    "title": title,
70
                    "text": "",
71
72
73
74
75
                    "fields": [
                        {
                            "title": "Job Name",
                            "value": job_name,
                            "short": True
76
                        },
77
78
79
80
                        {
                            "title": "Project",
                            "value": self.project_name,
                            "short": True,
81
                        },
82
83
84
85
                        {
                            "title": "Status",
                            "value": status,
                            "short": True
86
                        },
87
88
89
90
                        {
                            "title": "Detail",
                            "value": detail,
                            "short": True
91
92
93
94
95
                        }
                    ]
                }
            ]
        }
xaingling's avatar
xaingling committed
96
97
98
99
        if title:
            sending_dict["attachments"][0]["title"] = title
        if text:
            sending_dict["attachments"][0]["text"] = text
100
        return sending_dict