scrapinghub / spidermon

Scrapy Extension for monitoring spiders execution.
https://spidermon.readthedocs.io
BSD 3-Clause "New" or "Revised" License
528 stars 96 forks source link

Fix permissions based errors when sending slack messages #306

Closed further-reading closed 2 years ago

further-reading commented 3 years ago

The current implementation of slack messaging causes errors when certain permissions are missing. The issue come from the following line

 self._client.chat_postMessage(
            channel=channel,
            text=text,
            parse=parse,
            link_names=link_names,
            attachments=self._parse_attachments(attachments),
            username=self.sender_name,
            icon_url=self.users[self.sender_name]["profile"]["image_48"], <------
        )

The icon_url argument is an optional argument when sending a slack message to change the avatar displayed when the message is sent. In order to find the content to place in this argument the code takes two steps

  1. Gets a dict that contains details of all users in a slack organisation.
  2. Searches for the SPIDERMON_SLACK_SENDER_NAME in in this dict.

However, these steps are prone to fail. First, to achieve step 1 the users:read permission needs to be added to the bot, but a bot that is intended to just write messages to slack should function with only the chat:write permission. Second, it is possible for some integrations to not appear in the specific list that spidermon is looking for users in, resulting in a key error when trying to grab its own details.

As I mentioned this is an optional argument - if this is not included in the slack chat_postMessage call then it just uses the icon that was set by the bot's developer. The only use case is when the bot is using an icon from another user/app within the organisation, which feels like it's probably an edge case. As such I propose adding error handling when attempting to find the icon_url so basic slack bots will work as expected.