Skip to content

Commit

Permalink
chore(slack): support attachments (#2691)
Browse files Browse the repository at this point in the history
  • Loading branch information
talboren authored Nov 28, 2024
1 parent 3457bd4 commit 613effa
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 30 deletions.
99 changes: 70 additions & 29 deletions keep/providers/slack_provider/slack_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ def _notify(
channel="",
slack_timestamp="",
thread_timestamp="",
attachments=[],
username="",
**kwargs: dict,
):
"""
Expand All @@ -136,43 +138,54 @@ def _notify(
"Message is required - see for example https://github.com/keephq/keep/blob/main/examples/workflows/slack_basic.yml#L16"
)
message = blocks[0].get("text")
if self.authentication_config.webhook_url:
response = requests.post(
self.authentication_config.webhook_url,
json={"text": message, "blocks": blocks},
payload = {
"channel": channel,
"text": message,
"blocks": (
json.dumps(blocks)
if isinstance(blocks, dict) or isinstance(blocks, list)
else blocks
),
}
if attachments:
payload["attachments"] = (
json.dumps(attachments)
if isinstance(attachments, dict) or isinstance(attachments, list)
else blocks
)
if username:
payload["username"] = username

if self.authentication_config.webhook_url:
# If attachments are present, we need to send them as the payload with nothing else
# Also, do not encode the payload as json, but as x-www-form-urlencoded
# Only reference I found for it is: https://getkeep.slack.com/services/B082F60L9GX?added=1 and
# https://stackoverflow.com/questions/42993602/slack-chat-postmessage-attachment-gives-no-text
if payload["attachments"]:
payload["attachments"] = attachments
response = requests.post(
self.authentication_config.webhook_url,
data={"payload": json.dumps(payload)},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
else:
response = requests.post(
self.authentication_config.webhook_url,
json=payload,
)
if not response.ok:
raise ProviderException(
f"{self.__class__.__name__} failed to notify alert message to Slack: {response.text}"
)
elif self.authentication_config.access_token:
if not channel:
raise ProviderException("Channel is required (E.g. C12345)")
payload["token"] = self.authentication_config.access_token
if slack_timestamp == "" and thread_timestamp == "":
self.logger.info("Sending a new message to Slack")
payload = {
"channel": channel,
"text": message,
"blocks": (
json.dumps(blocks)
if isinstance(blocks, dict) or isinstance(blocks, list)
else blocks
),
"token": self.authentication_config.access_token,
}
method = "chat.postMessage"
else:
self.logger.info(f"Updating Slack message with ts: {slack_timestamp}")
payload = {
"channel": channel,
"text": message,
"blocks": (
json.dumps(blocks)
if isinstance(blocks, dict) or isinstance(blocks, list)
else blocks
),
"token": self.authentication_config.access_token,
}
if slack_timestamp:
payload["ts"] = slack_timestamp
method = "chat.update"
Expand Down Expand Up @@ -238,15 +251,43 @@ def _notify(
)
provider.notify(
message="Simple alert showing context with name: John Doe",
channel="alerts-playground",
channel="C04P7QSG692",
blocks=[
{
"type": "header",
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Danny Torrence left the following review for your property:",
},
},
{
"type": "section",
"block_id": "section567",
"text": {
"type": "plain_text",
"text": "Alert! :alarm_clock:",
"emoji": True,
"type": "mrkdwn",
"text": "<https://example.com|Overlook Hotel> \n :star: \n Doors had too many axe holes, guest in room 237 was far too rowdy, whole place felt stuck in the 1920s.",
},
"accessory": {
"type": "image",
"image_url": "https://is5-ssl.mzstatic.com/image/thumb/Purple3/v4/d3/72/5c/d3725c8f-c642-5d69-1904-aa36e4297885/source/256x256bb.jpg",
"alt_text": "Haunted hotel image",
},
},
{
"type": "section",
"block_id": "section789",
"fields": [{"type": "mrkdwn", "text": "*Average Rating*\n1.0"}],
},
],
attachments=[
{
"fallback": "Plain-text summary of the attachment.",
"color": "#2eb886",
"title": "Slack API Documentation",
"title_link": "https://api.slack.com/",
"text": "Optional text that appears within the attachment",
"footer": "Slack API",
"footer_icon": "https://platform.slack-edge.com/img/default_application_icon.png",
}
],
)
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "keep"
version = "0.30.4"
version = "0.30.5"
description = "Alerting. for developers, by developers."
authors = ["Keep Alerting LTD"]
packages = [{include = "keep"}]
Expand Down

0 comments on commit 613effa

Please sign in to comment.