feat(slack): add Blocks API support with "body_format" variable

pull/1337/head
John Torakis 2025-05-18 13:23:26 +03:00
parent ae7f8b80ac
commit fcbd086121
1 changed files with 31 additions and 10 deletions

View File

@ -76,6 +76,7 @@ import re
import requests import requests
from json import dumps from json import dumps
from json import loads from json import loads
from json import JSONDecodeError
from time import time from time import time
from .base import NotifyBase from .base import NotifyBase
@ -410,18 +411,30 @@ class NotifySlack(NotifyBase):
if self.notify_format == NotifyFormat.MARKDOWN \ if self.notify_format == NotifyFormat.MARKDOWN \
else 'plain_text' else 'plain_text'
payload = { # If we have to handle Blocks API serialized JSON
'username': self.user if self.user else self.app_id, if kwargs.get('body_format', None) == 'json':
'attachments': [{ try:
'blocks': [{ content = loads(body)
except JSONDecodeError:
self.logger.error(
"'body_format' is set as 'json',"
"but body is not valid JSON string"
)
return False
# Else, we continue as before
else:
content = {'blocks': [{
'type': 'section', 'type': 'section',
'text': { 'text': {
'type': _slack_format, 'type': _slack_format,
'text': body 'text': body
} }
}], }]}
'color': self.color(notify_type), content.update({'color': self.color(notify_type)})
}]
payload = {
'username': self.user if self.user else self.app_id,
'attachments': [content.copy()]
} }
# Slack only accepts non-empty header sections # Slack only accepts non-empty header sections
@ -463,6 +476,14 @@ class NotifySlack(NotifyBase):
payload['attachments'][0]['blocks'].append(_footer) payload['attachments'][0]['blocks'].append(_footer)
else: else:
# We do not support JSON body without the Blocks API
if kwargs.get('body_format', None) == 'json':
self.logger.error(
"'body_format' is set as 'json',"
"the 'blocks' URL parameter is not set"
)
return False
# #
# Legacy API Formatting # Legacy API Formatting
# #