From 4a7c181e915776236c3fd48eb91a0a3cfc29a7d4 Mon Sep 17 00:00:00 2001 From: Aaron Bach Date: Fri, 21 Aug 2020 08:37:30 -0600 Subject: [PATCH] Allow Slack notifications to change username/icon on the fly (#39091) * Allow Slack notifications to change username/icon on the fly * Code review --- homeassistant/components/slack/notify.py | 27 +++++++++++++++++------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/slack/notify.py b/homeassistant/components/slack/notify.py index a06785e506f..d43a1fc25ad 100644 --- a/homeassistant/components/slack/notify.py +++ b/homeassistant/components/slack/notify.py @@ -27,10 +27,12 @@ _LOGGER = logging.getLogger(__name__) ATTR_BLOCKS = "blocks" ATTR_BLOCKS_TEMPLATE = "blocks_template" ATTR_FILE = "file" +ATTR_ICON = "icon" ATTR_PASSWORD = "password" ATTR_PATH = "path" ATTR_URL = "url" ATTR_USERNAME = "username" +ATTR_USERNAME = "username" CONF_DEFAULT_CHANNEL = "default_channel" @@ -51,7 +53,12 @@ DATA_FILE_SCHEMA = vol.Schema( ) DATA_TEXT_ONLY_SCHEMA = vol.Schema( - {vol.Optional(ATTR_BLOCKS): list, vol.Optional(ATTR_BLOCKS_TEMPLATE): list} + { + vol.Optional(ATTR_USERNAME): cv.string, + vol.Optional(ATTR_ICON): cv.string, + vol.Optional(ATTR_BLOCKS): list, + vol.Optional(ATTR_BLOCKS_TEMPLATE): list, + } ) DATA_SCHEMA = vol.All( @@ -191,11 +198,10 @@ class SlackNotificationService(BaseNotificationService): except ClientError as err: _LOGGER.error("Error while uploading file message: %s", err) - async def _async_send_text_only_message(self, targets, message, title, blocks): + async def _async_send_text_only_message( + self, targets, message, title, blocks, username, icon + ): """Send a text-only message.""" - username = self._username - icon = self._icon - if self._icon.lower().startswith(("http://", "https://")): icon_type = "url" else: @@ -204,10 +210,10 @@ class SlackNotificationService(BaseNotificationService): tasks = { target: self._client.chat_postMessage( **{ - "channel": target, - "text": message, "blocks": blocks, + "channel": target, "link_names": True, + "text": message, "username": username, f"icon_{icon_type}": icon, } @@ -252,7 +258,12 @@ class SlackNotificationService(BaseNotificationService): blocks = {} return await self._async_send_text_only_message( - targets, message, title, blocks + targets, + message, + title, + blocks, + username=data.get(ATTR_USERNAME, self._username), + icon=data.get(ATTR_ICON, self._icon), ) # Message Type 2: A message that uploads a remote file