Merge pull request #1523 from paihu/slack-color-notification

support slack color notification #1490
This commit is contained in:
Matthew Jones
2018-03-19 18:05:28 -07:00
committed by GitHub
3 changed files with 50 additions and 1 deletions

View File

@@ -20,9 +20,12 @@ class SlackBackend(AWXBaseEmailBackend):
recipient_parameter = "channels"
sender_parameter = None
def __init__(self, token, fail_silently=False, **kwargs):
def __init__(self, token, hex_color="", fail_silently=False, **kwargs):
super(SlackBackend, self).__init__(fail_silently=fail_silently)
self.token = token
self.color = None
if hex_color.startswith("#") and (len(hex_color) == 4 or len(hex_color) == 7):
self.color = hex_color
self.connection = None
def open(self):
@@ -51,6 +54,37 @@ class SlackBackend(AWXBaseEmailBackend):
self.connection = None
def send_messages(self, messages):
if self.color:
return self._send_attachments(messages)
else:
return self._send_rtm_messages(messages)
def _send_attachments(self, messages):
connection = SlackClient(self.token)
sent_messages = 0
for m in messages:
try:
for r in m.recipients():
if r.startswith('#'):
r = r[1:]
ret = connection.api_call("chat.postMessage",
channel=r,
attachments=[{
"color": self.color,
"text": m.subject
}])
logger.debug(ret)
if ret['ok']:
sent_messages += 1
else:
raise RuntimeError("Slack Notification unable to send {}: {}".format(r, m.subject))
except Exception as e:
logger.error(smart_text(_("Exception sending messages: {}").format(e)))
if not self.fail_silently:
raise
return sent_messages
def _send_rtm_messages(self, messages):
if self.connection is None:
self.open()
sent_messages = 0