Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

slack_data_import: Support converting integration bot messages.

PieterCK0dfb70915262
diff --git a/zerver/data_import/slack.py b/zerver/data_import/slack.py
index 84c6d16c7ee..73cd68399ac 100644
--- a/zerver/data_import/slack.py
+++ b/zerver/data_import/slack.py
@@ -46,6 +46,7 @@ from zerver.data_import.sequencer import NEXT_ID
from zerver.data_import.slack_message_conversion import (
convert_to_zulip_markdown,
get_user_full_name,
+ process_slack_block_and_attachment,
)
from zerver.lib.emoji import codepoint_to_name, get_emoji_file_name
from zerver.lib.export import MESSAGE_BATCH_CHUNK_SIZE, do_common_export_processes
@@ -940,6 +941,15 @@ def channel_message_to_zerver_message(
]:
continue
+ formatted_block = process_slack_block_and_attachment(message)
+
+ # Leave it as is if formatted_block is an empty string, it's likely
+ # one of the unhandled_types.
+ if formatted_block != "":
+ # For most cases, the value of message["text"] will be just an
+ # empty string.
+ message["text"] = formatted_block
+
try:
content, mentioned_user_ids, has_link = convert_to_zulip_markdown(
message["text"], users, added_channels, slack_user_id_to_zulip_user_id
@@ -1291,6 +1301,8 @@ def get_message_sending_user(message: ZerverFieldsT) -> str | None:
return message["user"]
if message.get("file"):
return message["file"].get("user")
+ if message.get("bot_id"):
+ return message.get("bot_id")
return None
diff --git a/zerver/data_import/slack_message_conversion.py b/zerver/data_import/slack_message_conversion.py
index bb4bc120666..45fd163d920 100644
--- a/zerver/data_import/slack_message_conversion.py
+++ b/zerver/data_import/slack_message_conversion.py
@@ -1,3 +1,4 @@
+import json
import re
from itertools import zip_longest
from typing import Any, Literal, TypeAlias, TypedDict, cast
@@ -13,6 +14,7 @@ from zerver.lib.validator import (
check_string,
check_string_in,
check_url,
+ to_wild_value,
)
# stubs
@@ -239,10 +241,25 @@ def convert_to_zulip_markdown(
def render_block(block: WildValue) -> str:
# https://api.slack.com/reference/block-kit/blocks
block_type = block["type"].tame(
- check_string_in(["actions", "context", "divider", "header", "image", "input", "section"])
+ check_string_in(
+ ["actions", "context", "divider", "header", "image", "input", "section", "rich_text"]
+ )
)
- if block_type == "actions":
- # Unhandled
+
+ unhandled_types = [
+ # The "actions" block is used to format literal in-message clickable
+ # buttons and similar elements, which Zulip currently doesn't support.
+ # https://docs.slack.dev/reference/block-kit/blocks/actions-block
+ "actions",
+ # All user-sent messages contain at least a "block" component with a
+ # "rich_text" block. This block contains the same string as the "text"
+ # field. We're skipping this because the Slack import tool already
+ # handles the "text" field and the Slack incoming integration
+ # overrides it.
+ # https://docs.slack.dev/reference/block-kit/blocks/rich-text-block/
+ "rich_text",
+ ]
+ if block_type in unhandled_types:
return ""
elif block_type == "context" and block.get("elements"):
pieces = []
@@ -389,3 +406,15 @@ def replace_links(text: str) -> str:
text, _ = convert_link_format(text)
text, _ = convert_mailto_format(text)
return text
+
+
+def process_slack_block_and_attachment(message: ZerverFieldsT) -> str:
+ slack_message: WildValue = to_wild_value("slack_message", json.dumps(message))
+ pieces: list[str] = []
+
+ if slack_message.get("blocks"):
+ pieces += map(render_block, slack_message["blocks"])
+
+ if slack_message.get("attachments"):
+ pieces += map(render_attachment, slack_message["attachments"])
+ return "\n".join(piece.strip() for piece in pieces if piece.strip() != "")
diff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.py
index 371043fb084..317d8bd3250 100644
--- a/zerver/tests/test_slack_importer.py
+++ b/zerver/tests/test_slack_importer.py
@@ -1462,6 +1462,188 @@ class SlackImporter(ZulipTestCase):
zerver_message[1]["recipient"], slack_recipient_name_to_zulip_recipient_id["random"]
)
+ @mock.patch("zerver.data_import.slack.build_usermessages", return_value=(2, 4))
+ def test_channel_message_to_zerver_message_with_integration_bots(
+ self, mock_build_usermessage: mock.Mock
+ ) -> None:
+ """
+ Most of the core logic for converting Slack blocks is in slack_incoming/test.py,
+ so the purpose for this test is to verify the import tool portion of this system.
+ """
+ user_data = [
+ {"id": "U066MTL5U", "name": "john doe", "deleted": False, "real_name": "John"},
+ {"id": "U061A5N1G", "name": "jane doe", "deleted": False, "real_name": "Jane"},
+ {
+ "id": "B06NWMNUQ3W", # Bot user
+ "name": "ClickUp",
+ "deleted": False,
+ "real_name": "ClickUp",
+ },
+ ]
+
+ slack_user_id_to_zulip_user_id = {"U066MTL5U": 5, "U061A5N1G": 24, "B06NWMNUQ3W": 43}
+
+ all_messages: list[dict[str, Any]] = [
+ {
+ "subtype": "bot_message",
+ "text": "",
+ "username": "ClickUp",
+ "attachments": [
+ {
+ "id": 1,
+ "color": "008844",
+ "fallback": "dsdaddsa",
+ "text": "Added assignee Pieter\n\nby Pieter\n_<https://app.clickup.com/25567147/v/s/43687023|Task one> &gt; <https://app.clickup.com/25567147/v/li/901601846060|dsad>_",
+ "title": "dsdaddsa",
+ "title_link": "https://app.clickup.com/t/86cv0v5my",
+ "mrkdwn_in": ["text"],
+ }
+ ],
+ "type": "message",
+ "ts": "1712027355.830689",
+ "bot_id": "B06NWMNUQ3W",
+ "app_id": "A3G4A68V9",
+ "channel_name": "general",
+ },
+ {
+ "subtype": "bot_message",
+ "text": "",
+ "username": "ClickUp",
+ "attachments": [
+ {
+ "id": 1,
+ "blocks": [
+ {
+ "type": "section",
+ "block_id": "qvtCh",
+ "text": {
+ "type": "mrkdwn",
+ "text": "<https://app.clickup.com/t/86cv0v5my| dsda>",
+ "verbatim": False,
+ },
+ },
+ {
+ "type": "section",
+ "block_id": "7LtRa",
+ "text": {
+ "type": "mrkdwn",
+ "text": "Task Created\nBy Pieter\n",
+ "verbatim": False,
+ },
+ },
+ {
+ "type": "section",
+ "block_id": "XgOBF",
+ "fields": [
+ {
+ "type": "mrkdwn",
+ "text": "_<https://app.clickup.com/25567147/v/s/43687023|Task one> &gt; <https://app.clickup.com/25567147/v/li/901601846060|dsad>_",
+ "verbatim": False,
+ }
+ ],
+ },
+ ],
+ "color": "#656f7d",
+ "fallback": "[no preview available]",
+ }
+ ],
+ "type": "message",
+ "ts": "1712026462.647119",
+ "bot_id": "B06NWMNUQ3W",
+ "app_id": "A3G4A68V9",
+ "channel_name": "general",
+ },
+ {
+ "subtype": "bot_message",
+ "text": "",
+ "username": "ClickUp",
+ "attachments": [
+ {
+ "id": 1,
+ "color": "656f7d",
+ "fallback": "Buy Ingredients!",
+ "text": "New comment: where can I buy it?\n\nby Pieter\n_<https://app.clickup.com/25567147/v/s/43687023|Task one> &gt; <https://app.clickup.com/25567147/v/li/901601846060|dsad>_",
+ "title": "Buy Ingredients!",
+ "title_link": "https://app.clickup.com/t/86cuy8e4y?comment=90160026391938",
+ "mrkdwn_in": ["text"],
+ }
+ ],
+ "type": "message",
+ "ts": "1711032565.114789",
+ "bot_id": "B06NWMNUQ3W",
+ "app_id": "A3G4A68V9",
+ "channel_name": "general",
+ },
+ ]
+
+ slack_recipient_name_to_zulip_recipient_id = {
+ "random": 2,
+ "general": 1,
+ }
+ dm_members: DMMembersT = {}
+
+ zerver_usermessage: list[dict[str, Any]] = []
+ subscriber_map: dict[int, set[int]] = {}
+ added_channels: dict[str, tuple[str, int]] = {"random": ("c5", 1), "general": ("c6", 2)}
+
+ (
+ zerver_message,
+ zerver_usermessage,
+ attachment,
+ uploads,
+ reaction,
+ ) = channel_message_to_zerver_message(
+ 1,
+ user_data,
+ slack_user_id_to_zulip_user_id,
+ slack_recipient_name_to_zulip_recipient_id,
+ all_messages,
+ [],
+ subscriber_map,
+ added_channels,
+ dm_members,
+ "domain",
+ set(),
+ convert_slack_threads=True,
+ )
+ # functioning already tested in helper function
+ self.assertEqual(zerver_usermessage, [])
+ # subtype: channel_join is filtered
+ self.assert_length(zerver_message, 3)
+
+ self.assertEqual(uploads, [])
+ self.assertEqual(attachment, [])
+
+ expected_message_attachment = """## [dsdaddsa](https://app.clickup.com/t/86cv0v5my)
+
+Added assignee Pieter
+
+by Pieter
+*[Task one](https://app.clickup.com/25567147/v/s/43687023) &gt; [dsad](https://app.clickup.com/25567147/v/li/901601846060)*
+""".strip()
+ self.assertEqual(zerver_message[0]["content"], expected_message_attachment)
+ self.assertEqual(zerver_message[0]["sender"], slack_user_id_to_zulip_user_id["B06NWMNUQ3W"])
+
+ expected_message_block = """[ dsda](https://app.clickup.com/t/86cv0v5my)
+
+Task Created
+By Pieter
+
+*[Task one](https://app.clickup.com/25567147/v/s/43687023) &gt; [dsad](https://app.clickup.com/25567147/v/li/901601846060)*
+""".strip()
+ self.assertEqual(zerver_message[1]["content"], expected_message_block)
+ self.assertEqual(zerver_message[1]["sender"], slack_user_id_to_zulip_user_id["B06NWMNUQ3W"])
+
+ expected_message_block_2 = """## [Buy Ingredients!](https://app.clickup.com/t/86cuy8e4y?comment=90160026391938)
+
+New comment: where can I buy it?
+
+by Pieter
+*[Task one](https://app.clickup.com/25567147/v/s/43687023) &gt; [dsad](https://app.clickup.com/25567147/v/li/901601846060)*
+""".strip()
+ self.assertEqual(zerver_message[2]["content"], expected_message_block_2)
+ self.assertEqual(zerver_message[2]["sender"], slack_user_id_to_zulip_user_id["B06NWMNUQ3W"])
+
@mock.patch("zerver.data_import.slack.channel_message_to_zerver_message")
@mock.patch("zerver.data_import.slack.get_messages_iterator")
def test_convert_slack_workspace_messages(