-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathslack_thread.py
More file actions
171 lines (128 loc) · 5.37 KB
/
Copy pathslack_thread.py
File metadata and controls
171 lines (128 loc) · 5.37 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
class SlackThread(object):
def __init__(self, channel, username):
self.thread_ts = None
self.initial_attachments = []
self.last_response = None
self.channel = channel
self.username = username
self.warnings = 0
self.errors = 0
self.exceptions = 0
def update_first_msg(self, color, message):
encoded = self.__encode(message)
json_payload = self.update_payload(color, encoded, self.initial_attachments)
self.__send(json_payload, post=False)
def send_msg(self, message, reply_broadcast=False):
encoded = self.__encode(message)
json_payload = self.chat_payload(reply_broadcast, "good", encoded, [])
self.__send(json_payload)
def send_warning(self, message, reply_broadcast=False):
encoded = self.__encode(message)
json_payload = self.chat_payload(reply_broadcast, "warning", encoded, [])
self.__send(json_payload)
self.warnings += 1
message, color = self.rebuild_first_message()
self.update_first_msg(color, self.__encode(message))
def send_error(self, message, reply_broadcast=False):
encoded = self.__encode(message)
json_payload = self.chat_payload(reply_broadcast, "danger", encoded, [])
self.__send(json_payload)
self.errors += 1
message, color = self.rebuild_first_message()
self.update_first_msg(color, self.__encode(message))
def send_exception(self, message, reply_broadcast=False):
import traceback
message = self.__encode(message)
error_msg = traceback.format_exc()
if str(error_msg).strip() != "NoneType: None":
message += "\n```{}```".format(error_msg)
json_payload = self.chat_payload(reply_broadcast, "danger", message, [])
self.__send(json_payload)
self.exceptions += 1
message, color = self.rebuild_first_message()
self.update_first_msg(color, self.__encode(message))
def rebuild_first_message(self):
label = ""
if self.exceptions > 0:
label += f" {self.exceptions} Exceptions |"
if self.errors > 0:
label += f" {self.errors} Errors |"
if self.warnings > 0:
label += f" {self.warnings} Warnings |"
label = label.strip()
parts = self.initial_attachments[0]["text"].split("|\n")
text = parts[-1].strip()
message = "| " +label + "\n" + text
color = "danger" if self.errors > 0 or self.exceptions > 0 else "warning"
return message, color
@staticmethod
def __headers():
import os
token = os.getenv("SLACK_OAUTH_ACCESS_TOKEN")
assert token is not None, "Slack's OAuth Access Token must be specified"
return {
"Accept": "application/json; charset=utf-8",
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Bearer " + token
}
def __send(self, json_payload, post=True, attempts=1):
import time
import requests
if attempts > 120:
print("Failed to send Slack message after 120 attempts")
elif attempts > 1:
time.sleep(1)
url = "https://slack.com/api/chat.postMessage" if post else "https://slack.com/api/chat.update"
response = requests.post(
url,
headers=self.__headers(),
json=json_payload)
if response.status_code == 429:
return self.__send(json_payload, post, attempts+1)
elif response.status_code != 200:
raise Exception("Unexpected response ({}):\n{}".format(response.status_code, response.text))
# Slack reports 200 even when it actually isn't...
# We have to go one step further and check the "ok" flag.
self.last_response = response.json()
if self.last_response["ok"] is not True:
msg = self.last_response["error"] if "error" in self.last_response else "Unknown error"
raise Exception("Unexpected response ({}):\n{}".format(response.status_code, msg))
self.channel = self.last_response["channel"]
if self.thread_ts is None:
self.thread_ts = response.json()["ts"]
self.initial_attachments = json_payload["attachments"]
@staticmethod
def __encode(text):
import re
"""
Encode: &, <, and > because slack uses these for control sequences.
"""
text = re.sub("&", "&", text)
text = re.sub("<", "<", text)
text = re.sub(">", ">", text)
return text
def update_payload(self, color, message, attachments):
attachments[0]["color"] = color
attachments[0]["text"] = message
ret_val = {
"channel": self.channel,
"username": self.username,
"attachments": attachments,
"ts": self.thread_ts
}
return ret_val
def chat_payload(self, reply_broadcast, color, message, attachments):
attachments.append({
"color": color,
"text": message,
"mrkdwn_in": ["text"],
})
ret_val = {
"channel": self.channel,
"username": self.username,
"reply_broadcast": reply_broadcast,
"attachments": attachments
}
if self.thread_ts:
ret_val["thread_ts"] = self.thread_ts
return ret_val