Skip to content

Commit

Permalink
fix(slack): message is not required with attachments (#2741)
Browse files Browse the repository at this point in the history
  • Loading branch information
talboren authored Dec 3, 2024
1 parent ddd475b commit c0ba444
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 63 deletions.
57 changes: 19 additions & 38 deletions keep/providers/slack_provider/slack_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class SlackProviderAuthConfig:
"required": True,
"description": "Slack Webhook Url",
"validation": "https_url",
"sensitive": True
"sensitive": True,
},
)
access_token: str = dataclasses.field(
Expand Down Expand Up @@ -134,20 +134,21 @@ def _notify(
},
)
if not message:
if not blocks:
if not blocks and not attachments:
raise ProviderException(
"Message is required - see for example https://github.com/keephq/keep/blob/main/examples/workflows/slack_basic.yml#L16"
)
message = blocks[0].get("text")
payload = {
"channel": channel,
"text": message,
"blocks": (
}
if message:
payload["text"] = message
if blocks:
payload["blocks"] = (
json.dumps(blocks)
if isinstance(blocks, dict) or isinstance(blocks, list)
else blocks
),
}
)
if attachments:
payload["attachments"] = (
json.dumps(attachments)
Expand Down Expand Up @@ -194,9 +195,17 @@ def _notify(
method = "chat.postMessage"
payload["thread_ts"] = thread_timestamp

response = requests.post(
f"{SlackProvider.SLACK_API}/{method}", data=payload
)
if payload["attachments"]:
payload["attachments"] = attachments
response = requests.post(
f"{SlackProvider.SLACK_API}/{method}",
data={"payload": json.dumps(payload)},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
else:
response = requests.post(
f"{SlackProvider.SLACK_API}/{method}", data=payload
)

response_json = response.json()
if not response.ok or not response_json.get("ok"):
Expand Down Expand Up @@ -251,35 +260,7 @@ def _notify(
provider_config=config,
)
provider.notify(
message="Simple alert showing context with name: John Doe",
channel="C04P7QSG692",
blocks=[
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Danny Torrence left the following review for your property:",
},
},
{
"type": "section",
"block_id": "section567",
"text": {
"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.",
Expand Down
50 changes: 26 additions & 24 deletions keep/providers/teams_provider/teams_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class TeamsProviderAuthConfig:
"required": True,
"description": "Teams Webhook Url",
"sensitive": True,
"validation": "https_url"
"validation": "https_url",
}
)

Expand Down Expand Up @@ -75,40 +75,42 @@ def _notify(
self.logger.debug("Notifying alert message to Teams")
webhook_url = self.authentication_config.webhook_url

if isinstance(sections, str):
if sections and isinstance(sections, str):
try:
sections = json.loads(sections)
except json.JSONDecodeError as e:
except Exception as e:
self.logger.error(f"Failed to decode sections string to JSON: {e}")

if attachments and isinstance(attachments, str):
try:
attachments = json.loads(attachments)
except json.JSONDecodeError as e:
except Exception as e:
self.logger.error(f"Failed to decode attachments string to JSON: {e}")

if typeCard == "message":
# Adaptive Card format
payload = {
"type": "message",
"attachments": attachments
or [
{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": schema,
"type": "AdaptiveCard",
"version": "1.2",
"body": (
sections
if sections
else [{"type": "TextBlock", "text": message}]
),
},
}
],
}
payload = {"type": "message"}
if attachments:
payload["attachments"] = attachments
else:
payload["attachments"] = (
[
{
"contentType": "application/vnd.microsoft.card.adaptive",
"contentUrl": None,
"content": {
"$schema": schema,
"type": "AdaptiveCard",
"version": "1.2",
"body": (
sections
if sections
else [{"type": "TextBlock", "text": message}]
),
},
}
],
)
else:
# Standard MessageCard format
payload = {
Expand Down
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.31.0"
version = "0.31.1"
description = "Alerting. for developers, by developers."
authors = ["Keep Alerting LTD"]
packages = [{include = "keep"}]
Expand Down

0 comments on commit c0ba444

Please sign in to comment.