diff --git a/elementary/messages/messaging_integrations/slack_web.py b/elementary/messages/messaging_integrations/slack_web.py index f83b2ae51..ecaf03bda 100644 --- a/elementary/messages/messaging_integrations/slack_web.py +++ b/elementary/messages/messaging_integrations/slack_web.py @@ -102,6 +102,7 @@ def _send_message( formatted_message: FormattedBlockKitMessage, thread_ts: Optional[str] = None, reply_broadcast: bool = False, + joined_channel: bool = False, ) -> MessageSendResult[SlackWebMessageContext]: try: response = self.client.chat_postMessage( @@ -113,8 +114,15 @@ def _send_message( reply_broadcast=reply_broadcast, ) except SlackApiError as e: - self._handle_send_err(e, destination) - return self._send_message(destination, formatted_message, thread_ts) + self._handle_send_err(e, destination, can_join=not joined_channel) + # The app has just joined the channel, so send the message again. + return self._send_message( + destination, + formatted_message, + thread_ts=thread_ts, + reply_broadcast=reply_broadcast, + joined_channel=True, + ) return MessageSendResult( message_context=SlackWebMessageContext( @@ -124,17 +132,20 @@ def _send_message( message_format="block_kit", ) - def _handle_send_err(self, err: SlackApiError, channel_name: str): + def _handle_send_err( + self, err: SlackApiError, channel_name: str, can_join: bool = True + ) -> None: if self.tracking: self.tracking.record_internal_exception(err) err_type = err.response.data["error"] - if err_type == "not_in_channel": + if err_type == "not_in_channel" and can_join: logger.info( f'Elementary app is not in the channel "{channel_name}". Attempting to join.' ) channel_id = self._get_channel_id(channel_name, only_public=True) self._join_channel(channel_id=channel_id) logger.info(f"Joined channel {channel_name}") + return elif err_type == "channel_not_found": raise MessagingIntegrationError( f"Channel {channel_name} was not found by the Elementary app. Please add the app to the channel." diff --git a/tests/unit/messages/messaging_integrations/test_slack_web.py b/tests/unit/messages/messaging_integrations/test_slack_web.py new file mode 100644 index 000000000..bdb53c380 --- /dev/null +++ b/tests/unit/messages/messaging_integrations/test_slack_web.py @@ -0,0 +1,110 @@ +from unittest.mock import MagicMock + +import pytest +from slack_sdk.errors import SlackApiError +from slack_sdk.web import SlackResponse + +from elementary.messages.blocks import HeaderBlock +from elementary.messages.message_body import MessageBody +from elementary.messages.messaging_integrations.exceptions import ( + MessagingIntegrationError, +) +from elementary.messages.messaging_integrations.slack_web import ( + SlackWebMessagingIntegration, +) + +CHANNEL_NAME = "data-alerts" +CHANNEL_ID = "C123" + + +def _slack_error(error: str) -> SlackApiError: + response = SlackResponse( + client=None, + http_verb="POST", + api_url="https://slack.com/api/chat.postMessage", + req_args={}, + data={"ok": False, "error": error}, + headers={}, + status_code=200, + ) + return SlackApiError(message=error, response=response) + + +def _posted_message() -> dict: + return {"ts": "1700000000.000100", "channel": CHANNEL_ID} + + +def _create_integration(client: MagicMock) -> SlackWebMessagingIntegration: + client.conversations_list.return_value = { + "channels": [{"name": CHANNEL_NAME, "id": CHANNEL_ID}], + "response_metadata": {"next_cursor": ""}, + } + return SlackWebMessagingIntegration(client=client, reply_broadcast=True) + + +def _body() -> MessageBody: + return MessageBody(blocks=[HeaderBlock(text="Test alert")]) + + +def test_send_message_joins_channel_and_retries_when_not_in_channel(): + client = MagicMock() + client.chat_postMessage.side_effect = [ + _slack_error("not_in_channel"), + _posted_message(), + ] + integration = _create_integration(client) + + result = integration.send_message(destination=CHANNEL_NAME, body=_body()) + + client.conversations_join.assert_called_once_with(channel=CHANNEL_ID) + assert client.chat_postMessage.call_count == 2 + assert result.message_context.id == "1700000000.000100" + assert result.message_context.channel == CHANNEL_ID + + +def test_reply_retry_after_join_keeps_thread_and_reply_broadcast(): + client = MagicMock() + client.chat_postMessage.side_effect = [ + _slack_error("not_in_channel"), + _posted_message(), + ] + integration = _create_integration(client) + context = integration.parse_message_context( + {"id": "1690000000.000100", "channel": CHANNEL_ID} + ) + + integration.reply_to_message( + destination=CHANNEL_NAME, message_context=context, body=_body() + ) + + first_kwargs = client.chat_postMessage.call_args_list[0].kwargs + retry_kwargs = client.chat_postMessage.call_args_list[1].kwargs + assert retry_kwargs["channel"] == first_kwargs["channel"] == CHANNEL_NAME + assert retry_kwargs["blocks"] == first_kwargs["blocks"] + assert retry_kwargs["attachments"] == first_kwargs["attachments"] + assert retry_kwargs["thread_ts"] == "1690000000.000100" + assert retry_kwargs["reply_broadcast"] is True + + +def test_send_message_raises_if_still_not_in_channel_after_join(): + client = MagicMock() + client.chat_postMessage.side_effect = _slack_error("not_in_channel") + integration = _create_integration(client) + + with pytest.raises(MessagingIntegrationError): + integration.send_message(destination=CHANNEL_NAME, body=_body()) + + client.conversations_join.assert_called_once_with(channel=CHANNEL_ID) + assert client.chat_postMessage.call_count == 2 + + +def test_send_message_raises_on_channel_not_found(): + client = MagicMock() + client.chat_postMessage.side_effect = _slack_error("channel_not_found") + integration = _create_integration(client) + + with pytest.raises(MessagingIntegrationError): + integration.send_message(destination=CHANNEL_NAME, body=_body()) + + client.conversations_join.assert_not_called() + assert client.chat_postMessage.call_count == 1