LANG-295: support Slack threads through standard message APIs (#2864)

* feat(slack): expose thread messaging and context APIs

Co-authored-by: multica-agent <[email protected]>

* fix(slack): preserve actual mentions in thread replies

Co-authored-by: multica-agent <[email protected]>

* feat(slack): use standard message APIs for threads

Co-authored-by: multica-agent <[email protected]>

* fix(slack): append thread quotes after message content

Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: multica-agent <[email protected]>
This commit is contained in:
RockChinQ
2026-11-04 18:58:52 +08:00
committed by GitHub
co-authored by multica-agent
parent ae63811182
commit dbe8b15679
10 changed files with 368 additions and 20 deletions
+12 -2
View File
@@ -79,11 +79,13 @@ If no reply arrives, check that both the bot and message route are enabled, the
## Events, interactions and upgrading existing apps
Quick setup configures the subscriptions and interaction endpoint below. Installation requests message, channel, user, file and reaction permissions; `reactions:read` enables reaction events. Normal channel replies still require an @mention. Subscribing to channel messages for edits, deletions and channel changes does not trigger replies to all channel traffic.
Quick setup configures the subscriptions and interaction endpoint below. Installation requests message, channel, user, file and reaction permissions; `reactions:read` enables reaction events. Replies in threads started by this bot are delivered without an @mention; other channel messages still require one. Subscribe to `message.channels` with `channels:history` (and `message.groups` with `groups:history` for private channels) to receive these thread replies. Reinstall the Slack app after adding scopes.
Thread delivery does not imply a bot mention. Unmentioned replies remain available to plugins but do not satisfy the default pipeline's mention-based group response rule.
| Slack event | LangBot event |
| --- | --- |
| Direct messages, `app_mention` | `message.received` |
| Direct messages, `app_mention`, replies in this bot's threads | `message.received` |
| `message_changed` / `message_deleted` message subtypes | `message.edited` / `message.deleted` |
| `reaction_added` / `reaction_removed` | `message.reaction`, distinguished by `is_add` |
| `member_joined_channel` / `member_left_channel` | `group.member_joined` / `group.member_left` |
@@ -105,6 +107,14 @@ Interactions are acknowledged first and processed asynchronously. Synchronous fi
See the [Slack App Manifest reference](https://docs.slack.dev/reference/app-manifest/) for field definitions.
## Threads with standard message APIs
Use `send_message` and `reply_message` with standard message components:
- `send_message` returns a `MessageResult` whose `message_id` is the first sent message's Slack `ts`, including when text is followed by a file. Save this ID to start a thread beneath that message.
- Include `Quote(id=message_id, origin=MessageChain([]))` in the outgoing chain to send text and files into that thread. The first Quote with a nonempty ID takes precedence, including over `reply_message`'s source thread or `quote_origin` selection. Its origin content is not sent. Without an explicit Quote ID, existing send/reply behavior is unchanged.
- Incoming channel thread replies include `Quote(id=thread_ts, group_id=channel, target_id=channel, origin=MessageChain([]))`. The current message's ID remains in `Source.id`. Root messages and messages outside threads have no thread Quote. Plugins can read the parent ID directly from the chain without a separate context lookup.
## Manual setup (Webhook)
The screenshots below show basic messaging setup. Use the current lists in “Events, interactions and upgrading existing apps” above for complete permissions, subscriptions and interactivity settings.
+12 -2
View File
@@ -79,11 +79,13 @@ Slack でアプリの **Messages** タブを開き、DM を送信します。ボ
## イベント、インタラクション、既存アプリの更新
クイック設定は以下の購読とインタラクションの受信設定を行います。インストール時にメッセージ、チャンネル、ユーザー、ファイル、リアクションの権限を要求し、リアクションには `reactions:read` を使用します。チャンネルの通常返信には引き続き @メンションが必要です。編集・削除やチャンネル変更のためのメッセージ購読によって、すべての会話に返信することはありません。
クイック設定は以下の購読とインタラクションの受信設定を行います。インストール時にメッセージ、チャンネル、ユーザー、ファイル、リアクションの権限を要求し、リアクションには `reactions:read` を使用します。このボットが開始したスレッドへの返信は @メンションなしで受信できます。他のチャンネルメッセージには引き続き @メンションが必要です。スレッド返信の受信には `message.channels` と `channels:history`、プライベートチャンネルにはさらに `message.groups` と `groups:history` が必要です。権限を追加したら Slack アプリを再インストールしてください。
スレッド返信の配信はボットへのメンションを意味しません。メンションのない返信もプラグインで処理できますが、デフォルトのパイプラインのメンションに基づくグループ応答条件は満たしません。
| Slack イベント | LangBot イベント |
| --- | --- |
| DM、`app_mention` | `message.received` |
| DM、`app_mention`、このボットが開始したスレッドへの返信 | `message.received` |
| `message_changed` / `message_deleted` サブタイプ | `message.edited` / `message.deleted` |
| `reaction_added` / `reaction_removed` | `message.reaction`、`is_add` で区別 |
| `member_joined_channel` / `member_left_channel` | `group.member_joined` / `group.member_left` |
@@ -105,6 +107,14 @@ Slack でアプリの **Messages** タブを開き、DM を送信します。ボ
各フィールドは [Slack App Manifest リファレンス](https://docs.slack.dev/reference/app-manifest/)を参照してください。
## 標準メッセージ API でスレッドを操作する
`send_message`、`reply_message` と標準メッセージコンポーネントを使用します。
- `send_message` が返す `MessageResult.message_id` は、最初に送信したメッセージの Slack `ts` です。テキストの後にファイルを送信する場合も同様です。この ID を保存して、そのメッセージの下にスレッドを作成できます。
- 送信チェーンに `Quote(id=message_id, origin=MessageChain([]))` を含めると、テキストとファイルをそのスレッドへ送信します。空でない ID を持つ最初の Quote が優先され、`reply_message` の元のスレッドや `quote_origin` の指定よりも優先します。origin の内容は送信しません。明示的な Quote ID がなければ、既存の送信・返信動作を維持します。
- 受信したチャンネルのスレッド返信には `Quote(id=thread_ts, group_id=channel, target_id=channel, origin=MessageChain([]))` が含まれます。現在のメッセージ ID は `Source.id` に残ります。スレッドの親メッセージとスレッド外のメッセージにはこの Quote は付きません。プラグインは別のコンテキスト照会なしで親メッセージ ID を取得できます。
## 手動設定(Webhook)
以下の画像は基本的な会話設定です。権限、イベント購読、インタラクションの完全な設定は、上の「イベント、インタラクション、既存アプリの更新」の最新リストを使用してください。
+12 -2
View File
@@ -79,11 +79,13 @@ Webhook 模式可跳过本步。长连接模式中,点击助手的 **打开应
## 事件、交互与已有应用升级
新版快速配置向导会自动配置下列事件订阅和交互入口。安装授权页会申请消息、频道、用户、文件和表情反应权限,其中 `reactions:read` 用于表情反应事件。频道中的普通回复仍只由 @ 机器人触发;为获取编辑、删除和频道信息变化而订阅的频道消息不会全部触发回复。
新版快速配置向导会自动配置下列事件订阅和交互入口。安装授权页会申请消息、频道、用户、文件和表情反应权限,其中 `reactions:read` 用于表情反应事件。在本机器人发起的 thread 中回复无需 @ 机器人;其他频道消息仍需 @。接收这些 thread 回复需要订阅 `message.channels` 并授权 `channels:history`;私有频道还需要 `message.groups` 和 `groups:history`。添加权限后需重新安装 Slack 应用。
派发 thread 回复不等于 @ 机器人。没有 @ 的回复仍可供插件处理,但不会满足默认流水线基于 @ 的群响应条件。
| Slack 事件 | LangBot 事件 |
| --- | --- |
| 私聊消息、`app_mention` | `message.received` |
| 私聊消息、`app_mention`、本机器人发起的 thread 中的回复 | `message.received` |
| `message_changed` / `message_deleted` 消息子类型 | `message.edited` / `message.deleted` |
| `reaction_added` / `reaction_removed` | `message.reaction`,通过 `is_add` 区分 |
| `member_joined_channel` / `member_left_channel` | `group.member_joined` / `group.member_left` |
@@ -105,6 +107,14 @@ Webhook 模式可跳过本步。长连接模式中,点击助手的 **打开应
字段定义参考 [Slack App Manifest](https://docs.slack.dev/reference/app-manifest/)。
## 使用标准消息 API 操作 thread
使用 `send_message`、`reply_message` 和标准消息组件:
- `send_message` 返回 `MessageResult`,其 `message_id` 为第一条发出消息的 Slack `ts`;文本后附文件时也取第一条消息。保存此 ID 即可在该消息下创建 thread。
- 出站消息链加入 `Quote(id=message_id, origin=MessageChain([]))`,文本和文件都会发到该 thread。取第一个 ID 非空的 Quote,优先于 `reply_message` 的来源 thread 或 `quote_origin` 选择,且不发送其 origin 内容。没有显式 Quote ID 时,原有发送和回复行为不变。
- 入站频道 thread 回复带有 `Quote(id=thread_ts, group_id=channel, target_id=channel, origin=MessageChain([]))`,当前消息 ID 仍在 `Source.id` 中。thread 根消息和非 thread 消息不带此 Quote,插件可直接从消息链读取父消息 ID,无需另查上下文。
## 手动配置(Webhook)
下方截图展示基础对话配置;完整权限、事件订阅和交互配置请使用上方“事件、交互与已有应用升级”中的最新清单。
+19 -1
View File
@@ -36,6 +36,7 @@ class SlackClient:
self.socket_client = None
self.socket_queue = asyncio.Queue(maxsize=100)
self.socket_seen = OrderedDict()
self.channel_message_seen = OrderedDict()
self.socket_stop = asyncio.Event()
self.socket_worker = None
@@ -102,8 +103,24 @@ class SlackClient:
await self._handle_message(SlackEvent(data), 'event')
elif raw.get('channel_type') == 'im' and kind == 'message':
await self._handle_message(SlackEvent.from_payload(data))
elif kind == 'app_mention':
elif kind == 'app_mention' or (
kind == 'message'
and raw.get('channel_type') in {'channel', 'group'}
and raw.get('thread_ts')
and self.bot_user_id
and raw.get('parent_user_id') == self.bot_user_id
):
key = (raw.get('channel'), raw.get('ts'))
if all(key):
if key in self.channel_message_seen:
return
self.channel_message_seen[key] = True
while len(self.channel_message_seen) > 4096:
self.channel_message_seen.popitem(last=False)
raw['channel_type'] = 'channel'
raw['mentioned'] = kind == 'app_mention' or bool(
self.bot_user_id and f'<@{self.bot_user_id}>' in (raw.get('text') or '')
)
await self._handle_message(SlackEvent.from_payload(data))
elif kind != 'message':
await self._handle_message(SlackEvent(data), 'event')
@@ -173,6 +190,7 @@ class SlackClient:
worker.cancel()
await asyncio.gather(worker, return_exceptions=True)
self.socket_seen.clear()
self.channel_message_seen.clear()
while not self.socket_queue.empty():
self.socket_queue.get_nowait()
self.socket_queue.task_done()
+17 -8
View File
@@ -99,10 +99,23 @@ async def send_chain(
if target_type not in {'person', 'channel'}:
raise ValueError(f'Unsupported Slack target type: {target_type}')
thread_ts = next(
(str(component.id) for component in chain if isinstance(component, pm.Quote) and component.id), thread_ts
)
responses = []
pending = []
channel = None
async def resolve_channel():
nonlocal channel
if channel is None:
if target_type == 'person' and not target_id.startswith('D'):
opened = await bot.client.conversations_open(users=[target_id])
channel = opened['channel']['id']
else:
channel = target_id
return channel
async def flush():
if not pending:
return
@@ -110,7 +123,9 @@ async def send_chain(
pending.clear()
if text:
if thread_ts:
response = await bot.client.chat_postMessage(channel=target_id, text=text, thread_ts=thread_ts)
response = await bot.client.chat_postMessage(
channel=await resolve_channel(), text=text, thread_ts=thread_ts
)
responses.append(response.data if hasattr(response, 'data') else response)
else:
method = bot.send_message_to_one if target_type == 'person' else bot.send_message_to_channel
@@ -120,14 +135,8 @@ async def send_chain(
if isinstance(component, MEDIA_TYPES):
data, filename = await attachment_bytes(component, bot.bot_token)
await flush()
if channel is None:
if target_type == 'person' and not target_id.startswith('D'):
opened = await bot.client.conversations_open(users=[target_id])
channel = opened['channel']['id']
else:
channel = target_id
response = await bot.client.files_upload_v2(
channel=channel,
channel=await resolve_channel(),
file=data,
filename=filename,
title=filename,
@@ -106,7 +106,11 @@ class SlackAdapter(SlackAPIMixin, abstract_platform_adapter.AbstractPlatformAdap
message: platform_message.MessageChain,
) -> platform_events.MessageResult:
raw = await send_chain(self.bot, self._normalize_target_type(str(target_type)), str(target_id), message)
return platform_events.MessageResult(raw=raw)
responses = raw.get('responses', [])
sent = responses[0] if responses else {}
return platform_events.MessageResult(
message_id=sent.get('ts') or sent.get('message', {}).get('ts', ''), raw=raw
)
async def reply_message(
self,
@@ -29,9 +29,7 @@ class SlackMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
elif isinstance(component, platform_message.File):
parts.append(component.url or component.name or component.id or '[File]')
elif isinstance(component, platform_message.Quote):
if component.id is not None:
parts.append(f'[Quote {component.id}]')
if component.origin:
if not component.id and component.origin:
parts.append(await SlackMessageConverter.yiri2target(component.origin))
elif isinstance(component, platform_message.Forward):
for node in component.node_list:
@@ -53,7 +51,8 @@ class SlackMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
)
]
if event.type == 'channel':
raw = event.get('event', {})
if event.type == 'channel' and (raw.get('type') == 'app_mention' or raw.get('mentioned')):
components.append(platform_message.At(target='SlackBot'))
for file in event.get('event', {}).get('files', []):
@@ -81,6 +80,17 @@ class SlackMessageConverter(abstract_platform_adapter.AbstractMessageConverter):
if len(components) == 1 or (len(components) == 2 and isinstance(components[1], platform_message.At)):
components.append(platform_message.Unknown(text=f'[unsupported slack event: {event.type or "unknown"}]'))
thread_ts = raw.get('thread_ts')
if event.type == 'channel' and thread_ts and thread_ts != raw.get('ts'):
components.append(
platform_message.Quote(
id=thread_ts,
group_id=event.channel_id,
target_id=event.channel_id,
origin=platform_message.MessageChain([]),
)
)
return platform_message.MessageChain(components)
@@ -103,3 +103,57 @@ async def test_preprocessor_keeps_image_placeholder_for_text_only_local_agent(mo
assert content[0].type == 'text'
assert content[0].text == '[Image]'
assert result.new_query.variables['user_message_text'] == '[Image]'
@pytest.mark.asyncio
@pytest.mark.parametrize('combine_quote', [False, True])
async def test_preprocessor_accepts_slack_thread_quote_with_empty_origin(mock_app, sample_query, combine_quote):
from importlib import import_module
from langbot.libs.slack_api.slackevent import SlackEvent
from langbot.pkg.platform.adapters.slack.message_converter import SlackMessageConverter
model = Mock()
model.model_entity.uuid = 'text-only-model'
model.model_entity.abilities = []
mock_app.model_mgr.get_model_by_uuid = AsyncMock(return_value=model)
_attach_runner_descriptor(mock_app)
mock_app.sess_mgr.get_session = AsyncMock(
return_value=provider_session.Session(
launcher_type=sample_query.launcher_type,
launcher_id=sample_query.launcher_id,
sender_id=sample_query.sender_id,
bot_uuid=sample_query.bot_uuid,
)
)
mock_app.sess_mgr.get_conversation = AsyncMock(return_value=_conversation())
mock_app.plugin_connector.emit_event = AsyncMock(return_value=_prompt_preprocessing_context())
sample_query.pipeline_config = _pipeline_config({'primary': 'text-only-model', 'fallbacks': []})
sample_query.pipeline_config['trigger']['misc']['combine-quote-message'] = combine_quote
sample_query.message_chain = await SlackMessageConverter.target2yiri(
SlackEvent(
{
'event': {
'type': 'message',
'channel_type': 'channel',
'channel': 'C-1',
'ts': '2.2',
'thread_ts': '1.1',
'text': 'reply',
}
}
)
)
quotes = [part for part in sample_query.message_chain if isinstance(part, platform_message.Quote)]
assert len(quotes) == 1
assert list(quotes[0].origin) == []
sample_query.messages = []
sample_query.variables = {}
import_module('langbot.pkg.pipeline.pipelinemgr')
preproc_module = import_module('langbot.pkg.pipeline.preproc.preproc')
result = await preproc_module.PreProcessor(mock_app).process(sample_query, 'PreProcessor')
content = result.new_query.user_message.content
assert len(content) == 1
assert content[0].type == 'text'
assert content[0].text == 'reply'
assert result.new_query.variables['user_message_text'] == 'reply'
@@ -88,6 +88,155 @@ def make_adapter() -> SlackAdapter:
return SlackAdapter(config, DummyLogger())
@pytest.mark.asyncio
@pytest.mark.parametrize('channel_type', ['channel', 'group'])
@pytest.mark.parametrize(
'kinds,text,is_thread,mentioned',
[
(('message',), 'just chatting, no mention', True, False),
(('message',), '<@OTHER> reply', True, False),
(('message', 'app_mention'), '<@B-1> reply', True, True),
(('app_mention', 'message'), '<@B-1> reply', True, True),
(('app_mention',), 'hello', False, True),
],
)
async def test_channel_dispatch_preserves_actual_bot_mention(channel_type, kinds, text, is_thread, mentioned):
adapter = SlackAdapter({'bot_token': 'test', 'signing_secret': 'test'}, DummyLogger())
received = AsyncMock()
legacy_received = AsyncMock()
adapter.register_listener(platform_events.MessageReceivedEvent, received)
adapter.register_listener(platform_events.GroupMessage, legacy_received)
for kind in kinds:
raw = {
'type': kind,
'channel_type': channel_type,
'channel': 'C-1',
'user': 'U-1',
'ts': '1710003600.000100',
'text': text,
}
if is_thread:
raw.update(thread_ts='1710003600.000001', parent_user_id='B-1')
await adapter.bot.handle_payload(
{'event': raw, 'event_id': kind, 'authorizations': [{'is_bot': True, 'user_id': 'B-1'}]}
)
for listener in (received, legacy_received):
listener.assert_awaited_once()
event = listener.await_args.args[0]
assert any(isinstance(part, platform_message.At) for part in event.message_chain) is mentioned
assert any(isinstance(part, platform_message.Plain) and part.text == text for part in event.message_chain)
quotes = [part for part in event.message_chain if isinstance(part, platform_message.Quote)]
assert [quote.id for quote in quotes] == (['1710003600.000001'] if is_thread else [])
assert received.await_args.args[0].message_id == '1710003600.000100'
@pytest.mark.asyncio
@pytest.mark.parametrize('with_file', [False, True])
async def test_send_message_returns_first_message_id(with_file):
adapter = make_adapter()
adapter.bot.client.files_upload_v2 = AsyncMock(return_value={'ok': True, 'files': [{'id': 'F-1'}]})
components = [platform_message.Plain(text='root')]
if with_file:
components.append(platform_message.File(name='test.txt', base64='dGVzdA=='))
result = await adapter.send_message('group', 'C-1', platform_message.MessageChain(components))
assert result.message_id == '1.1'
assert len(result.raw['responses']) == (2 if with_file else 1)
assert adapter.bot.sent == [('channel', 'C-1', 'root')]
@pytest.mark.asyncio
@pytest.mark.parametrize('target_type,target_id,channel', [('group', 'C-1', 'C-1'), ('person', 'U-1', 'D-1')])
@pytest.mark.parametrize('with_file', [False, True])
async def test_send_message_quote_routes_text_and_files(target_type, target_id, channel, with_file):
adapter = make_adapter()
adapter.bot.client.chat_postMessage = AsyncMock(return_value={'ok': True, 'ts': '4.4'})
adapter.bot.client.files_upload_v2 = AsyncMock(return_value={'ok': True, 'files': [{'id': 'F-1'}]})
adapter.bot.client.conversations_open = AsyncMock(return_value={'ok': True, 'channel': {'id': 'D-1'}})
components = [
platform_message.Plain(text='reply'),
platform_message.Quote(
id='2.2', origin=platform_message.MessageChain([platform_message.Plain(text='quoted context')])
),
platform_message.Quote(id='3.3', origin=platform_message.MessageChain([])),
]
if with_file:
components.append(platform_message.File(name='test.txt', base64='dGVzdA=='))
result = await adapter.send_message(target_type, target_id, platform_message.MessageChain(components))
assert result.message_id == '4.4'
adapter.bot.client.chat_postMessage.assert_awaited_once_with(channel=channel, text='reply', thread_ts='2.2')
if with_file:
adapter.bot.client.files_upload_v2.assert_awaited_once_with(
channel=channel, file=b'test', filename='test.txt', title='test.txt', thread_ts='2.2'
)
else:
adapter.bot.client.files_upload_v2.assert_not_awaited()
if target_type == 'person':
adapter.bot.client.conversations_open.assert_awaited_once_with(users=['U-1'])
else:
adapter.bot.client.conversations_open.assert_not_awaited()
assert adapter.bot.sent == []
@pytest.mark.asyncio
@pytest.mark.parametrize('source_thread,quote_origin', [(None, False), (None, True), ('2.2', False)])
@pytest.mark.parametrize('explicit_quote', [False, True])
async def test_reply_message_quote_takes_priority(source_thread, quote_origin, explicit_quote):
adapter = make_adapter()
adapter.bot.client.chat_postMessage = AsyncMock(return_value={'ok': True, 'ts': '4.4'})
native = slack_event('channel')
if source_thread:
native['event']['thread_ts'] = source_thread
source = await adapter.event_converter.target2yiri(native)
components = [platform_message.Plain(text='reply')]
if explicit_quote:
components.append(platform_message.Quote(id='3.3', origin=platform_message.MessageChain([])))
result = await adapter.reply_message(source, platform_message.MessageChain(components), quote_origin)
expected_thread = '3.3' if explicit_quote else source_thread or (source.message_id if quote_origin else None)
if expected_thread:
adapter.bot.client.chat_postMessage.assert_awaited_once_with(
channel='C-1', text='reply', thread_ts=expected_thread
)
assert result.message_id == '4.4'
else:
adapter.bot.client.chat_postMessage.assert_not_awaited()
assert adapter.bot.sent == [('channel', 'C-1', 'reply')]
@pytest.mark.asyncio
@pytest.mark.parametrize('thread_ts', [None, '1710003600.000100', '1710003600.000001'])
async def test_inbound_thread_quote(thread_ts):
native = slack_event('channel')
if thread_ts:
native['event']['thread_ts'] = thread_ts
event = await SlackEventConverter().target2yiri(native)
quotes = [part for part in event.message_chain if isinstance(part, platform_message.Quote)]
if thread_ts and thread_ts != native.message_id:
assert len(quotes) == 1
assert quotes[0].id == thread_ts
assert quotes[0].group_id == quotes[0].target_id == 'C-1'
assert list(quotes[0].origin) == []
assert event.message_chain[-1] is quotes[0]
else:
assert quotes == []
@pytest.mark.asyncio
async def test_thread_command_prefix_survives_removing_bot_mention():
native = slack_event('channel', text='!help')
native['event']['thread_ts'] = '1.0'
chain = await SlackMessageConverter.target2yiri(native)
assert [type(part) for part in chain] == [
platform_message.Source,
platform_message.At,
platform_message.Plain,
platform_message.Quote,
]
without_mention = platform_message.MessageChain(
[part for part in chain if not isinstance(part, platform_message.At)]
)
assert str(without_mention).strip().startswith('!help')
def slack_event(channel_type: str = 'im', **overrides) -> SlackEvent:
text = overrides.get('text', 'hello')
payload = {
@@ -146,6 +295,7 @@ def test_slack_platform_api_map_matches_manifest():
manifest_actions = {item['action'] for item in manifest()['spec']['platform_specific_apis']}
assert set(PLATFORM_API_MAP) == manifest_actions
assert manifest_actions == {'get_mode', 'auth_test'}
@pytest.mark.asyncio
@@ -7,6 +7,79 @@ import pytest
from langbot.libs.slack_api.api import SlackClient
def thread_payload(**overrides):
return {
'event': {
'type': 'message',
'channel_type': 'channel',
'channel': 'C-1',
'user': 'U-1',
'ts': '1710003600.000100',
'thread_ts': '1710003600.000001',
'parent_user_id': 'B-1',
'text': 'reply without mention',
**overrides,
}
}
@pytest.mark.asyncio
@pytest.mark.parametrize('channel_type', ['channel', 'group'])
@pytest.mark.parametrize('subtype', [None, 'file_share', 'thread_broadcast'])
async def test_bot_thread_replies_dispatch_without_mention(channel_type, subtype):
bot = SlackClient('test', '', SimpleNamespace(), unified_mode=True)
received = AsyncMock()
bot.on_message('channel')(received)
payload = thread_payload(channel_type=channel_type, subtype=subtype)
payload['authorizations'] = [{'is_bot': True, 'user_id': 'B-1'}]
await bot.handle_payload(payload)
received.assert_awaited_once()
assert received.await_args.args[0]['event']['thread_ts'] == '1710003600.000001'
@pytest.mark.asyncio
@pytest.mark.parametrize(
'overrides',
[
{'parent_user_id': 'other-user'},
{'parent_user_id': None},
{'thread_ts': None},
{'bot_id': 'B-2'},
],
)
async def test_unrelated_channel_messages_are_ignored(overrides):
bot = SlackClient('test', '', SimpleNamespace(), unified_mode=True)
bot.bot_user_id = 'B-1'
bot._handle_message = AsyncMock()
await bot.handle_payload(thread_payload(**overrides))
bot._handle_message.assert_not_awaited()
@pytest.mark.asyncio
@pytest.mark.parametrize('kinds', [('message', 'app_mention'), ('app_mention', 'message')])
async def test_bot_thread_mention_is_dispatched_once(kinds):
bot = SlackClient('test', '', SimpleNamespace(), unified_mode=True)
bot.bot_user_id = 'B-1'
received = AsyncMock()
bot.on_message('channel')(received)
for kind in kinds:
payload = thread_payload(type=kind, text='<@B-1> reply')
payload['event_id'] = kind
await bot.handle_payload(payload)
received.assert_awaited_once()
await bot.handle_payload(thread_payload(channel='C-2'))
assert received.await_count == 2
@pytest.mark.asyncio
async def test_thread_edits_keep_event_dispatch():
bot = SlackClient('test', '', SimpleNamespace(), unified_mode=True)
bot.bot_user_id = 'B-1'
bot._handle_message = AsyncMock()
await bot.handle_payload(thread_payload(subtype='message_changed'))
assert bot._handle_message.await_args.args[1] == 'event'
@pytest.mark.asyncio
async def test_socket_ack_dedup_and_backpressure():
bot = SlackClient('test', '', SimpleNamespace(warning=AsyncMock(), error=AsyncMock()), unified_mode=True)