-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadapter.py
More file actions
3373 lines (2910 loc) · 136 KB
/
adapter.py
File metadata and controls
3373 lines (2910 loc) · 136 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Slack adapter for chat-sdk.
Supports single-workspace (bot token) and multi-workspace (OAuth) modes.
All conversations use Slack threads as the unit of isolation.
Python port of packages/adapter-slack/src/index.ts.
"""
from __future__ import annotations
import asyncio
import base64
import contextvars
import hashlib
import hmac
import inspect
import json
import os
import re
import time
from collections import OrderedDict
from collections.abc import AsyncIterable, Awaitable, Callable
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any, NoReturn, cast
from urllib.parse import parse_qs, urlparse
from chat_sdk.adapters.slack.cards import (
card_to_block_kit,
card_to_fallback_text,
)
from chat_sdk.adapters.slack.crypto import (
EncryptedTokenData,
decode_key,
decrypt_token,
encrypt_token,
is_encrypted_token_data,
)
from chat_sdk.adapters.slack.format_converter import SlackFormatConverter
from chat_sdk.adapters.slack.modals import (
ModalMetadata,
SlackModalResponse,
decode_modal_metadata,
encode_modal_metadata,
modal_to_slack_view,
)
from chat_sdk.adapters.slack.types import (
RequestContext,
SlackAdapterConfig,
SlackInstallation,
SlackThreadId,
)
from chat_sdk.emoji import convert_emoji_placeholders, emoji_to_slack, resolve_emoji_from_slack
from chat_sdk.logger import ConsoleLogger, Logger
from chat_sdk.modals import ModalElement, SelectOptionElement
from chat_sdk.shared.adapter_utils import extract_card, extract_files
from chat_sdk.shared.errors import AdapterRateLimitError, AuthenticationError, ValidationError
from chat_sdk.types import (
ActionEvent,
AdapterPostableMessage,
AppHomeOpenedEvent,
AssistantContextChangedEvent,
AssistantThreadStartedEvent,
Attachment,
Author,
ChannelInfo,
ChannelVisibility,
ChatInstance,
EmojiValue,
EphemeralMessage,
FetchOptions,
FetchResult,
FileUpload,
FormattedContent,
LinkPreview,
ListThreadsOptions,
ListThreadsResult,
LockScope,
MemberJoinedChannelEvent,
Message,
MessageMetadata,
ModalCloseEvent,
ModalResponse,
ModalSubmitEvent,
OptionsLoadEvent,
RawMessage,
ReactionEvent,
ScheduledMessage,
SlashCommandEvent,
StreamChunk,
StreamOptions,
ThreadInfo,
ThreadSummary,
WebhookOptions,
)
# Slack expects block_suggestion responses within 3s. Leave headroom for
# network latency so the HTTP response lands before Slack gives up.
OPTIONS_LOAD_TIMEOUT_MS = 2500
# Strong-reference set for fire-and-forget tasks to prevent GC collection.
_background_tasks: set[asyncio.Task[Any]] = set()
def _pin_task(task: asyncio.Task[Any]) -> None:
"""Pin a fire-and-forget task so the GC doesn't collect it."""
_background_tasks.add(task)
task.add_done_callback(_background_tasks.discard)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
SLACK_USER_ID_PATTERN = re.compile(r"^[A-Z0-9_]+$")
SLACK_USER_ID_EXACT_PATTERN = re.compile(r"^U[A-Z0-9]+$")
SLACK_MESSAGE_URL_PATTERN = re.compile(r"^https?://[^/]+\.slack\.com/archives/([A-Z0-9]+)/p(\d+)(?:\?.*)?$")
# Cache TTLs (milliseconds)
_USER_CACHE_TTL_MS = 8 * 24 * 60 * 60 * 1000 # 8 days
_CHANNEL_CACHE_TTL_MS = 8 * 24 * 60 * 60 * 1000
_REVERSE_INDEX_TTL_MS = 8 * 24 * 60 * 60 * 1000
# Ignored message subtypes (system/meta events).
# `message_changed` is NOT in this set — it is routed to
# `_handle_message_changed` so we can capture link unfurl metadata.
_IGNORED_SUBTYPES = frozenset(
{
"message_deleted",
"message_replied",
"channel_join",
"channel_leave",
"channel_topic",
"channel_purpose",
"channel_name",
"channel_archive",
"channel_unarchive",
"group_join",
"group_leave",
"group_topic",
"group_purpose",
"group_name",
"group_archive",
"group_unarchive",
"ekm_access_denied",
"tombstone",
}
)
# Link-unfurl wait window: Slack delivers unfurled attachments via a
# separate `message_changed` event ~100-2000ms after the original. We
# poll briefly so the message handler sees enriched links instead of
# bare URLs.
_TRAILING_SLASH_PATTERN = re.compile(r"/$")
_UNFURL_WAIT_MS = 2000
_UNFURL_POLL_MS = 150
_UNFURL_CACHE_TTL_MS = 60 * 60 * 1000 # 1 hour
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _find_next_mention(text: str) -> int:
"""Find the next ``<@`` or ``<#`` mention in *text*."""
at_idx = text.find("<@")
hash_idx = text.find("<#")
if at_idx == -1:
return hash_idx
if hash_idx == -1:
return at_idx
return min(at_idx, hash_idx)
# ---------------------------------------------------------------------------
# Adapter
# ---------------------------------------------------------------------------
class SlackAdapter:
"""Slack adapter for chat-sdk.
Implements the Adapter interface for the Slack Web API.
Supports both single-workspace (static bot token) and multi-workspace
(per-team OAuth token lookup) modes.
"""
# ------------------------------------------------------------------
# Construction
# ------------------------------------------------------------------
def __init__(self, config: SlackAdapterConfig | None = None) -> None:
# ContextVar replaces Node AsyncLocalStorage for per-request token context.
# Created per-instance so multiple SlackAdapter instances don't share state.
self._request_context: ContextVar[RequestContext | None] = ContextVar(
f"slack_request_context_{id(self)}", default=None
)
if config is None:
config = SlackAdapterConfig()
signing_secret = config.signing_secret or os.environ.get("SLACK_SIGNING_SECRET")
if not signing_secret:
raise ValidationError(
"slack",
"signingSecret is required. Set SLACK_SIGNING_SECRET or provide it in config.",
)
# Auth fields: botToken presence selects single-workspace mode.
zero_config = not (config.signing_secret or config.bot_token or config.client_id or config.client_secret)
bot_token = config.bot_token or (os.environ.get("SLACK_BOT_TOKEN") if zero_config else None)
self._name = "slack"
self._signing_secret = signing_secret
self._default_bot_token: str | None = bot_token
self._logger: Logger = config.logger or ConsoleLogger("info")
self._user_name: str = config.user_name or "bot"
self._bot_user_id: str | None = config.bot_user_id or None
self._bot_id: str | None = None # Bot app ID (B_xxx)
self._chat: ChatInstance | None = None
self._format_converter = SlackFormatConverter()
self._lock_scope: LockScope = "thread"
self._persist_message_history = False
# Channel external/shared cache
self._external_channels: set[str] = set()
# Cache of AsyncWebClient instances keyed by bot token (LRU-bounded)
self._client_cache: OrderedDict[str, Any] = OrderedDict()
self._client_cache_max = config.client_cache_max if config.client_cache_max is not None else 100
# Multi-workspace OAuth fields
self._client_id: str | None = config.client_id or (os.environ.get("SLACK_CLIENT_ID") if zero_config else None)
self._client_secret: str | None = config.client_secret or (
os.environ.get("SLACK_CLIENT_SECRET") if zero_config else None
)
self._installation_key_prefix = config.installation_key_prefix or "slack:installation"
encryption_key_raw = config.encryption_key or os.environ.get("SLACK_ENCRYPTION_KEY")
self._encryption_key: bytes | None = None
if encryption_key_raw:
self._encryption_key = decode_key(encryption_key_raw)
# ------------------------------------------------------------------
# Properties (Adapter protocol)
# ------------------------------------------------------------------
@property
def name(self) -> str:
return self._name
@property
def user_name(self) -> str:
return self._user_name
@property
def bot_user_id(self) -> str | None:
ctx = self._request_context.get()
if ctx and ctx.bot_user_id:
return ctx.bot_user_id
return self._bot_user_id
@property
def lock_scope(self) -> LockScope:
return self._lock_scope
@property
def persist_message_history(self) -> bool:
return self._persist_message_history
# ------------------------------------------------------------------
# Public request-context accessors
#
# These are Python-only extensions to the Adapter surface. They let
# code running inside a handler call the Slack Web API directly —
# e.g. ``users.info`` for caller-email resolution — without
# reaching into the underscore-prefixed ``_get_token`` /
# ``_get_client`` helpers. See docs/UPSTREAM_SYNC.md.
# ------------------------------------------------------------------
@property
def current_token(self) -> str:
"""Return the bot token bound to the current request context.
In multi-workspace mode this is the token resolved by the
``InstallationStore`` for the current request; in single-workspace
mode it is the default bot token. Raises
:class:`AuthenticationError` when called outside a request context
with no default token configured.
"""
return self._get_token()
@property
def current_client(self) -> Any:
"""Return an ``AsyncWebClient`` preconfigured with :attr:`current_token`.
Return type is ``Any`` (rather than the concrete
``AsyncWebClient``) because ``slack_sdk`` is an optional
dependency — consumers who install the SDK without the `slack`
extra shouldn't pay a type-check-time import cost. Docstring
captures the actual runtime type for tooling that reads it.
The returned client is LRU-cached by token. Raises
:class:`AuthenticationError` when no token is available.
"""
return self._get_client()
# ------------------------------------------------------------------
# Token management
# ------------------------------------------------------------------
def _get_token(self) -> str:
"""Return the current bot token for API calls.
Checks request context (multi-workspace) -> default token (single-workspace) -> raises.
"""
ctx = self._request_context.get()
if ctx and ctx.token:
return ctx.token
if self._default_bot_token:
return self._default_bot_token
raise AuthenticationError(
"slack",
"No bot token available. In multi-workspace mode, ensure the webhook is being processed.",
)
def _get_client(self, token: str | None = None) -> Any:
"""Return an ``AsyncWebClient`` for the given (or current) token.
Clients are cached by token so we avoid creating a new instance on
every request. The import is deferred so that ``slack_sdk`` is only
required at call-time.
When *token* is explicitly passed (even as ``""``) it is used as-is;
only when *token* is ``None`` do we fall back to ``_get_token()``.
"""
resolved_token = self._get_token() if token is None else token
if resolved_token in self._client_cache:
self._client_cache.move_to_end(resolved_token)
return self._client_cache[resolved_token]
from slack_sdk.web.async_client import AsyncWebClient
client = AsyncWebClient(token=resolved_token)
self._client_cache[resolved_token] = client
if len(self._client_cache) > self._client_cache_max:
# Evict oldest (LRU). We intentionally do NOT close the evicted
# client's session here because other concurrent requests may still
# hold a reference to the evicted AsyncWebClient instance. The
# underlying aiohttp.ClientSession will be closed by the garbage
# collector (via __del__) once all references are released.
self._client_cache.popitem(last=False)
return client
def _invalidate_client(self, token: str) -> None:
"""Remove a cached client (e.g., on token revocation)."""
self._client_cache.pop(token, None)
# ------------------------------------------------------------------
# Initialization
# ------------------------------------------------------------------
async def initialize(self, chat: ChatInstance) -> None:
"""Initialize the adapter and optionally fetch bot identity."""
self._chat = chat
# Single-workspace: fetch bot user ID via auth.test
if self._default_bot_token and not self._bot_user_id:
try:
client = self._get_client(self._default_bot_token)
auth_result = await client.auth_test()
self._bot_user_id = auth_result.get("user_id")
self._bot_id = auth_result.get("bot_id") or None
user = auth_result.get("user")
if user:
self._user_name = user
self._logger.info(
"Slack auth completed",
{"botUserId": self._bot_user_id, "botId": self._bot_id},
)
except Exception as exc:
self._logger.warn("Could not fetch bot user ID", {"error": exc})
if not self._default_bot_token:
self._logger.info("Slack adapter initialized in multi-workspace mode")
async def disconnect(self) -> None:
"""No persistent connections to close."""
# ==================================================================
# Multi-workspace installation management
# ==================================================================
def _installation_key(self, team_id: str) -> str:
return f"{self._installation_key_prefix}:{team_id}"
async def set_installation(self, team_id: str, installation: SlackInstallation) -> None:
"""Save a workspace installation (call from your OAuth callback)."""
if not self._chat:
raise ValidationError(
"slack",
"Adapter not initialized. Ensure chat.initialize() has been called first.",
)
state = self._chat.get_state()
key = self._installation_key(team_id)
if self._encryption_key:
encrypted = encrypt_token(installation.bot_token, self._encryption_key)
data_to_store: dict[str, Any] = {
"botToken": {
"iv": encrypted.iv,
"data": encrypted.data,
"tag": encrypted.tag,
},
"botUserId": installation.bot_user_id,
"teamName": installation.team_name,
}
else:
data_to_store = {
"botToken": installation.bot_token,
"botUserId": installation.bot_user_id,
"teamName": installation.team_name,
}
await state.set(key, data_to_store)
self._logger.info(
"Slack installation saved",
{"teamId": team_id, "teamName": installation.team_name},
)
async def get_installation(self, team_id: str) -> SlackInstallation | None:
"""Retrieve a workspace installation."""
if not self._chat:
raise ValidationError(
"slack",
"Adapter not initialized. Ensure chat.initialize() has been called first.",
)
state = self._chat.get_state()
key = self._installation_key(team_id)
stored = await state.get(key)
if not stored:
return None
bot_token_raw = (stored.get("botToken") or stored.get("bot_token")) if isinstance(stored, dict) else None
bot_user_id = (stored.get("botUserId") or stored.get("bot_user_id") or "") if isinstance(stored, dict) else ""
team_name = (stored.get("teamName") or stored.get("team_name") or "") if isinstance(stored, dict) else ""
if self._encryption_key and is_encrypted_token_data(bot_token_raw):
# `is_encrypted_token_data` is a runtime type guard but doesn't
# carry TypeGuard narrowing, so pyrefly still sees `None`. Assert
# to collapse the Optional for the field access below.
assert bot_token_raw is not None
decrypted = decrypt_token(
EncryptedTokenData(
iv=bot_token_raw["iv"],
data=bot_token_raw["data"],
tag=bot_token_raw["tag"],
),
self._encryption_key,
)
return SlackInstallation(
bot_token=decrypted,
bot_user_id=bot_user_id,
team_name=team_name,
)
return SlackInstallation(
bot_token=bot_token_raw if isinstance(bot_token_raw, str) else "",
bot_user_id=bot_user_id,
team_name=team_name,
)
async def handle_oauth_callback(
self,
request: Any,
options: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Handle the Slack OAuth V2 callback.
Args:
request: The incoming HTTP request containing the OAuth callback.
options: Optional dict with ``redirect_uri`` key to send to Slack
during the code exchange. When provided it takes priority over
any ``redirect_uri`` query parameter in the callback URL.
Returns ``{"team_id": ..., "installation": SlackInstallation}``.
"""
if not (self._client_id and self._client_secret):
raise ValidationError(
"slack",
"client_id and client_secret are required for OAuth. Pass them in create_slack_adapter().",
)
# Extract query params from request
url: str = getattr(request, "url", "")
if isinstance(url, str) and "?" in url:
query = dict(parse_qs(url.split("?", 1)[1]))
code = query.get("code", [None])[0] if isinstance(query.get("code"), list) else query.get("code")
query_redirect_uri = (
query.get("redirect_uri", [None])[0]
if isinstance(query.get("redirect_uri"), list)
else query.get("redirect_uri")
)
else:
code = None
query_redirect_uri = None
if not code:
raise ValidationError(
"slack",
"Missing 'code' query parameter in OAuth callback request.",
)
# Options redirect_uri takes priority over the query param
redirect_uri = (options or {}).get("redirect_uri") or query_redirect_uri
client = self._get_client("")
kwargs: dict[str, Any] = {
"client_id": self._client_id,
"client_secret": self._client_secret,
"code": code,
}
if redirect_uri:
kwargs["redirect_uri"] = redirect_uri
result = await client.oauth_v2_access(**kwargs)
if not (result.get("ok") and result.get("access_token") and result.get("team", {}).get("id")):
raise AuthenticationError(
"slack",
f"Slack OAuth failed: {result.get('error') or 'missing access_token or team.id'}",
)
team_id = result["team"]["id"]
installation = SlackInstallation(
bot_token=result["access_token"],
bot_user_id=result.get("bot_user_id"),
team_name=result.get("team", {}).get("name"),
)
await self.set_installation(team_id, installation)
return {"team_id": team_id, "installation": installation}
async def delete_installation(self, team_id: str) -> None:
"""Remove a workspace installation."""
if not self._chat:
raise ValidationError(
"slack",
"Adapter not initialized. Ensure chat.initialize() has been called first.",
)
state = self._chat.get_state()
await state.delete(self._installation_key(team_id))
self._logger.info("Slack installation deleted", {"teamId": team_id})
def with_bot_token(self, token: str, fn: Callable[[], Any]) -> Any:
"""Run *fn* with a specific bot token in context (for cron jobs, etc.)."""
tok = self._request_context.set(RequestContext(token=token))
try:
return fn()
finally:
self._request_context.reset(tok)
async def with_bot_token_async(self, token: str, fn: Callable[[], Awaitable[Any]]) -> Any:
"""Run an async function with a specific bot token in context."""
tok = self._request_context.set(RequestContext(token=token))
try:
return await fn()
finally:
self._request_context.reset(tok)
# ==================================================================
# Private helpers - token resolution
# ==================================================================
async def _resolve_token_for_team(self, team_id: str) -> RequestContext | None:
"""Resolve the bot token for a team from the state adapter."""
try:
installation = await self.get_installation(team_id)
if installation:
return RequestContext(
token=installation.bot_token,
bot_user_id=installation.bot_user_id,
)
self._logger.warn("No installation found for team", {"teamId": team_id})
return None
except Exception as exc:
self._logger.error("Failed to resolve token for team", {"teamId": team_id, "error": exc})
return None
def _extract_team_id_from_interactive(self, body: str) -> str | None:
"""Extract team_id from an interactive payload (form-urlencoded)."""
try:
params = parse_qs(body)
payload_str = params.get("payload", [None])[0]
if not payload_str:
return None
payload = json.loads(payload_str)
return payload.get("team", {}).get("id") or payload.get("team_id")
except Exception:
return None
# ==================================================================
# User / Channel lookup with caching
# ==================================================================
async def _lookup_user(self, user_id: str) -> dict[str, str]:
"""Look up user info from Slack API with caching.
Returns ``{"display_name": ..., "real_name": ...}``.
"""
cache_key = f"slack:user:{user_id}"
if self._chat:
cached = await self._chat.get_state().get(cache_key)
if cached and isinstance(cached, dict):
return {
"display_name": cached.get("display_name", user_id),
"real_name": cached.get("real_name", user_id),
}
try:
client = self._get_client()
result = await client.users_info(user=user_id)
user = result.get("user", {})
profile = user.get("profile", {})
display_name = (
profile.get("display_name")
or profile.get("real_name")
or user.get("real_name")
or user.get("name")
or user_id
)
real_name = user.get("real_name") or profile.get("real_name") or display_name
if self._chat:
await self._chat.get_state().set(
cache_key,
{"display_name": display_name, "real_name": real_name},
_USER_CACHE_TTL_MS,
)
# Reverse index: display name -> user IDs
normalized_name = display_name.lower()
reverse_key = f"slack:user-by-name:{normalized_name}"
existing = await self._chat.get_state().get_list(reverse_key)
if user_id not in existing:
await self._chat.get_state().append_to_list(
reverse_key,
user_id,
max_length=50,
ttl_ms=_REVERSE_INDEX_TTL_MS,
)
self._logger.debug(
"Fetched user info",
{"userId": user_id, "displayName": display_name, "realName": real_name},
)
return {"display_name": display_name, "real_name": real_name}
except Exception as exc:
self._logger.warn("Could not fetch user info", {"userId": user_id, "error": exc})
return {"display_name": user_id, "real_name": user_id}
async def _lookup_channel(self, channel_id: str) -> str:
"""Look up channel name from Slack API with caching."""
cache_key = f"slack:channel:{channel_id}"
if self._chat:
cached = await self._chat.get_state().get(cache_key)
if cached and isinstance(cached, dict):
return cached.get("name", channel_id)
try:
client = self._get_client()
result = await client.conversations_info(channel=channel_id)
channel = result.get("channel", {})
name = channel.get("name", channel_id)
if self._chat:
await self._chat.get_state().set(cache_key, {"name": name}, _CHANNEL_CACHE_TTL_MS)
self._logger.debug("Fetched channel info", {"channelId": channel_id, "name": name})
return name
except Exception as exc:
self._logger.warn("Could not fetch channel info", {"channelId": channel_id, "error": exc})
return channel_id
# ==================================================================
# Webhook handling
# ==================================================================
async def handle_webhook(self, request: Any, options: WebhookOptions | None = None) -> dict[str, Any]:
"""Handle incoming webhooks from Slack.
Handles URL verification, event callbacks, interactive payloads,
and slash commands.
Returns a dict with ``body`` and ``status`` keys.
"""
# Read the raw body. `hasattr` narrows `Any` → `object` (not
# awaitable), so we use `getattr(..., None)` to preserve the
# `Any` type across the duck-typed framework branches.
# Handle both callable (`async def text(self)`) and non-callable
# (`text: str` attribute) forms of `request.text`. Gating entry
# on callability would drop populated string attributes.
text_attr = getattr(request, "text", None)
body: str
if text_attr is not None:
if callable(text_attr):
result = text_attr()
text_attr = await result if inspect.isawaitable(result) else result
body = text_attr.decode("utf-8") if isinstance(text_attr, (bytes, bytearray)) else str(text_attr)
else:
raw = getattr(request, "body", None)
if raw is not None:
# Some frameworks expose `body` as an async method (e.g.
# `async def body(self)`) — call it, then await if the
# result is awaitable. Previously we only handled the
# coroutine-as-attribute case, not the async-method case.
if callable(raw):
raw = raw()
if asyncio.iscoroutine(raw) or asyncio.isfuture(raw) or inspect.isawaitable(raw):
raw = await raw
body = raw.decode("utf-8") if isinstance(raw, (bytes, bytearray)) else str(raw)
else:
body = str(request)
self._logger.debug("Slack webhook raw body", {"body": body[:500]})
# Extract headers
headers = getattr(request, "headers", {})
timestamp = headers.get("x-slack-request-timestamp") or headers.get("X-Slack-Request-Timestamp")
signature = headers.get("x-slack-signature") or headers.get("X-Slack-Signature")
if not self._verify_signature(body, timestamp, signature):
return {"body": "Invalid signature", "status": 401}
# Form-urlencoded payloads (interactive + slash commands)
content_type = headers.get("content-type") or headers.get("Content-Type") or ""
if "application/x-www-form-urlencoded" in content_type:
params = parse_qs(body, keep_blank_values=True)
# Slash command
if "command" in params and "payload" not in params:
team_id = (params.get("team_id") or [None])[0]
if not self._default_bot_token and team_id:
ctx = await self._resolve_token_for_team(team_id)
if ctx:
tok = self._request_context.set(ctx)
try:
return await self._handle_slash_command(params, options)
finally:
self._request_context.reset(tok)
self._logger.warn("Could not resolve token for slash command")
return await self._handle_slash_command(params, options)
# Interactive payload
if not self._default_bot_token:
team_id_interactive = self._extract_team_id_from_interactive(body)
if team_id_interactive:
ctx = await self._resolve_token_for_team(team_id_interactive)
if ctx:
tok = self._request_context.set(ctx)
try:
return await self._handle_interactive_payload(body, options)
finally:
self._request_context.reset(tok)
self._logger.warn("Could not resolve token for interactive payload")
return await self._handle_interactive_payload(body, options)
# JSON payload
try:
payload: dict[str, Any] = json.loads(body)
except (json.JSONDecodeError, ValueError):
return {"body": "Invalid JSON", "status": 400}
# URL verification challenge
if payload.get("type") == "url_verification" and payload.get("challenge"):
return {
"body": json.dumps({"challenge": payload["challenge"]}),
"status": 200,
"headers": {"Content-Type": "application/json"},
}
# Multi-workspace: resolve token before processing events.
# Use contextvars.copy_context() so the ContextVar value persists into
# any async tasks spawned by _process_event_payload (e.g. process_message
# creates a task via asyncio.create_task). The copied context is
# isolated -- the ContextVar change does not leak back to the caller
# and does not need an explicit reset.
if not self._default_bot_token and payload.get("type") == "event_callback":
team_id_event = payload.get("team_id")
if team_id_event:
ctx = await self._resolve_token_for_team(team_id_event)
if ctx:
isolated = contextvars.copy_context()
isolated.run(self._request_context.set, ctx)
isolated.run(self._process_event_payload, payload, options)
return {"body": "ok", "status": 200}
self._logger.warn("Could not resolve token for team", {"teamId": team_id_event})
return {"body": "ok", "status": 200}
# Single-workspace mode or fallback
self._process_event_payload(payload, options)
return {"body": "ok", "status": 200}
# ==================================================================
# Signature verification
# ==================================================================
def _verify_signature(self, body: str, timestamp: str | None, signature: str | None) -> bool:
if not (timestamp and signature):
return False
# Check timestamp is recent (within 5 minutes)
now = int(time.time())
try:
ts_int = int(timestamp)
except (ValueError, TypeError):
return False
if abs(now - ts_int) > 300:
return False
sig_basestring = f"v0:{timestamp}:{body}"
expected = (
"v0="
+ hmac.new(
self._signing_secret.encode("utf-8"),
sig_basestring.encode("utf-8"),
hashlib.sha256,
).hexdigest()
)
try:
return hmac.compare_digest(signature, expected)
except Exception:
return False
# ==================================================================
# Event dispatch
# ==================================================================
def _process_event_payload(self, payload: dict[str, Any], options: WebhookOptions | None = None) -> None:
"""Extract and dispatch events from a validated payload."""
if payload.get("type") != "event_callback" or not payload.get("event"):
return
event: dict[str, Any] = payload["event"]
# Track external/shared channel status
if payload.get("is_ext_shared_channel"):
channel_id = event.get("channel") or (event.get("item", {}).get("channel") if "item" in event else None)
if channel_id:
self._external_channels.add(channel_id)
event_type = event.get("type", "")
if event_type in ("message", "app_mention"):
if not (event.get("team") or event.get("team_id")) and payload.get("team_id"):
event["team_id"] = payload["team_id"]
self._handle_message_event(event, options)
elif event_type in ("reaction_added", "reaction_removed"):
self._handle_reaction_event(event, options)
elif event_type == "assistant_thread_started":
self._handle_assistant_thread_started(event, options)
elif event_type == "assistant_thread_context_changed":
self._handle_assistant_context_changed(event, options)
elif event_type == "app_home_opened" and event.get("tab") == "home":
self._handle_app_home_opened(event, options)
elif event_type == "member_joined_channel":
self._handle_member_joined_channel(event, options)
elif event_type == "user_change":
self._handle_user_change(event)
# ==================================================================
# Interactive payloads
# ==================================================================
async def _handle_interactive_payload(self, body: str, options: WebhookOptions | None = None) -> dict[str, Any]:
params = parse_qs(body, keep_blank_values=True)
payload_str = (params.get("payload") or [None])[0]
if not payload_str:
return {"body": "Missing payload", "status": 400}
try:
payload: dict[str, Any] = json.loads(payload_str)
except (json.JSONDecodeError, ValueError):
return {"body": "Invalid payload JSON", "status": 400}
payload_type = payload.get("type")
if payload_type == "block_actions":
self._handle_block_actions(payload, options)
return {"body": "", "status": 200}
elif payload_type == "block_suggestion":
return await self._handle_block_suggestion(payload, options)
elif payload_type == "view_submission":
return await self._handle_view_submission(payload, options)
elif payload_type == "view_closed":
self._handle_view_closed(payload, options)
return {"body": "", "status": 200}
return {"body": "", "status": 200}
# ==================================================================
# Slash commands
# ==================================================================
async def _handle_slash_command(
self,
params: dict[str, list[str]],
options: WebhookOptions | None = None,
) -> dict[str, Any]:
if not self._chat:
self._logger.warn("Chat instance not initialized, ignoring slash command")
return {"body": "", "status": 200}
command = (params.get("command") or [""])[0]
text = (params.get("text") or [""])[0]
user_id = (params.get("user_id") or [""])[0]
channel_id = (params.get("channel_id") or [""])[0]
trigger_id = (params.get("trigger_id") or [None])[0]
self._logger.debug(
"Processing Slack slash command",
{"command": command, "text": text, "userId": user_id, "channelId": channel_id},
)
user_info = await self._lookup_user(user_id)
event = SlashCommandEvent(
command=command,
text=text,
user=Author(
user_id=user_id,
user_name=user_info["display_name"],
full_name=user_info["real_name"],
is_bot=False,
is_me=False,
),
adapter=self,
channel=None, # pyrefly: ignore[bad-argument-type] # filled in by Chat
raw={k: v[0] for k, v in params.items()} if params else {},
trigger_id=trigger_id,
)
# Attach channel_id so chat.py can build a ChannelImpl
event.channel_id = f"slack:{channel_id}" if channel_id else "" # type: ignore[attr-defined]
self._chat.process_slash_command(event, options)
return {"body": "", "status": 200}
# ==================================================================
# Block actions
# ==================================================================
def _handle_block_actions(self, payload: dict[str, Any], options: WebhookOptions | None = None) -> None:
if not self._chat:
self._logger.warn("Chat instance not initialized, ignoring action")
return
channel = (payload.get("channel") or {}).get("id") or (payload.get("container") or {}).get("channel_id")
message_ts = (payload.get("message") or {}).get("ts") or (payload.get("container") or {}).get("message_ts")
thread_ts = (
(payload.get("message") or {}).get("thread_ts")
or (payload.get("container") or {}).get("thread_ts")
or message_ts
)
is_view_action = (payload.get("container") or {}).get("type") == "view"
if not (is_view_action or channel):
self._logger.warn("Missing channel in block_actions", {"channel": channel})
return
thread_id = ""
if channel and (thread_ts or message_ts):
thread_id = self.encode_thread_id(SlackThreadId(channel=channel, thread_ts=thread_ts or message_ts or ""))
is_ephemeral = (payload.get("container") or {}).get("is_ephemeral") is True
response_url = payload.get("response_url")
user_ref = payload.get("user") or {}
message_id: str
if is_ephemeral and response_url and message_ts:
message_id = self._encode_ephemeral_message_id(message_ts, response_url, user_ref.get("id", ""))
else:
message_id = message_ts or ""
for action in payload.get("actions", []):
action_value = (action.get("selected_option") or {}).get("value") or action.get("value")
action_event = ActionEvent(
action_id=action.get("action_id", ""),
value=action_value,
user=Author(
user_id=user_ref.get("id", ""),
user_name=user_ref.get("username") or user_ref.get("name") or "unknown",
full_name=user_ref.get("name") or user_ref.get("username") or "unknown",
is_bot=False,
is_me=False,
),