-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat.py
More file actions
1979 lines (1671 loc) · 75.5 KB
/
Copy pathchat.py
File metadata and controls
1979 lines (1671 loc) · 75.5 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
"""Chat orchestrator for chat-sdk.
Python port of Vercel Chat SDK chat.ts + chat-singleton.ts.
Main entry point: takes a ChatConfig, registers event handlers via decorator-style
methods, routes webhooks to adapters, manages concurrency, deduplication, and
thread/channel creation.
"""
from __future__ import annotations
import asyncio
import re
import uuid
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
from chat_sdk.channel import ChannelImpl
from chat_sdk.errors import ChatError, LockError
from chat_sdk.logger import ConsoleLogger, Logger
from chat_sdk.thread import (
ThreadImpl,
_ThreadImplConfig,
get_chat_singleton,
has_chat_singleton,
set_chat_singleton,
)
from chat_sdk.types import (
ActionEvent,
Adapter,
AppHomeOpenedEvent,
AssistantContextChangedEvent,
AssistantThreadStartedEvent,
Author,
ChannelVisibility,
ChatConfig,
ConcurrencyStrategy,
EmojiValue,
Lock,
LockScope,
LockScopeContext,
MemberJoinedChannelEvent,
Message,
MessageContext,
MessageMetadata,
ModalCloseEvent,
ModalResponse,
ModalSubmitEvent,
OnLockConflict,
QueueEntry,
ReactionEvent,
SlashCommandEvent,
StateAdapter,
WebhookOptions,
)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
DEFAULT_LOCK_TTL_MS = 30_000 # 30 seconds
DEDUPE_TTL_MS = 5 * 60 * 1000 # 5 minutes
MODAL_CONTEXT_TTL_MS = 24 * 60 * 60 * 1000 # 24 hours
SLACK_USER_ID_REGEX = re.compile(r"^U[A-Z0-9]+$", re.IGNORECASE)
DISCORD_SNOWFLAKE_REGEX = re.compile(r"^\d{17,19}$")
# ---------------------------------------------------------------------------
# Handler type aliases
# ---------------------------------------------------------------------------
MentionHandler = Callable[[Any, Message, Any], Awaitable[None] | None]
DirectMessageHandler = Callable[[Any, Message, Any, Any], Awaitable[None] | None]
MessageHandler = Callable[[Any, Message, Any], Awaitable[None] | None]
SubscribedMessageHandler = Callable[[Any, Message, Any], Awaitable[None] | None]
ReactionHandler = Callable[[ReactionEvent], Any]
ActionHandler = Callable[[ActionEvent], Any]
ModalSubmitHandler = Callable[[ModalSubmitEvent], Any]
ModalCloseHandler = Callable[[ModalCloseEvent], Any]
SlashCommandHandler = Callable[[SlashCommandEvent], Any]
AssistantThreadStartedHandler = Callable[[AssistantThreadStartedEvent], Any]
AssistantContextChangedHandler = Callable[[AssistantContextChangedEvent], Any]
AppHomeOpenedHandler = Callable[[AppHomeOpenedEvent], Any]
MemberJoinedChannelHandler = Callable[[MemberJoinedChannelEvent], Any]
EmojiFilter = EmojiValue | str
# ---------------------------------------------------------------------------
# Internal pattern types
# ---------------------------------------------------------------------------
class _MessagePattern:
__slots__ = ("pattern", "handler")
def __init__(self, pattern: re.Pattern[str], handler: MessageHandler) -> None:
self.pattern = pattern
self.handler = handler
class _ReactionPattern:
__slots__ = ("emoji", "handler")
def __init__(self, emoji: list[EmojiFilter], handler: ReactionHandler) -> None:
self.emoji = emoji
self.handler = handler
class _ActionPattern:
__slots__ = ("action_ids", "handler")
def __init__(self, action_ids: list[str], handler: ActionHandler) -> None:
self.action_ids = action_ids
self.handler = handler
class _ModalSubmitPattern:
__slots__ = ("callback_ids", "handler")
def __init__(self, callback_ids: list[str], handler: ModalSubmitHandler) -> None:
self.callback_ids = callback_ids
self.handler = handler
class _ModalClosePattern:
__slots__ = ("callback_ids", "handler")
def __init__(self, callback_ids: list[str], handler: ModalCloseHandler) -> None:
self.callback_ids = callback_ids
self.handler = handler
class _SlashCommandPattern:
__slots__ = ("commands", "handler")
def __init__(self, commands: list[str], handler: SlashCommandHandler) -> None:
self.commands = commands
self.handler = handler
# ---------------------------------------------------------------------------
# Stored modal context
# ---------------------------------------------------------------------------
class _StoredModalContext:
__slots__ = ("thread", "message", "channel")
def __init__(
self,
thread: dict[str, Any] | None = None,
message: dict[str, Any] | None = None,
channel: dict[str, Any] | None = None,
) -> None:
self.thread = thread
self.message = message
self.channel = channel
# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
async def _sleep(ms: int) -> None:
"""Promise-based sleep for debounce timing."""
await asyncio.sleep(ms / 1000.0)
def _create_task(coro: Any) -> asyncio.Task[Any] | None:
"""Create an asyncio task using the running loop.
Returns ``None`` when no event loop is running (e.g. called from a
synchronous context without an active loop). Callers should guard
against this.
"""
try:
loop = asyncio.get_running_loop()
return loop.create_task(coro)
except RuntimeError:
# No running event loop -- cannot schedule the coroutine.
# Close the coroutine to avoid "coroutine was never awaited" warning.
coro.close()
return None
# ---------------------------------------------------------------------------
# Chat class
# ---------------------------------------------------------------------------
class Chat:
"""Main Chat orchestrator.
Takes a ``ChatConfig`` and provides decorator-style registration for
event handlers (mentions, DMs, reactions, actions, modals, slash commands,
assistant events, etc.).
Routes incoming webhooks to adapters and manages concurrency, deduplication,
and locking.
Example::
chat = Chat(ChatConfig(
user_name="mybot",
adapters={"slack": slack_adapter},
state=memory_state,
))
@chat.on_mention
async def handle_mention(thread, message):
await thread.subscribe()
await thread.post("Hello!")
# In your web framework
@app.post("/slack/events")
async def slack_events(request):
return await chat.webhooks["slack"](request)
"""
def __init__(self, config: ChatConfig | None = None, **kwargs: Any) -> None:
if config is None:
config = ChatConfig(**kwargs)
self._user_name = config.user_name
self._state_adapter = config.state
self._adapters: dict[str, Adapter] = {}
self._streaming_update_interval_ms = config.streaming_update_interval_ms
self._fallback_streaming_placeholder_text = config.fallback_streaming_placeholder_text
self._dedupe_ttl_ms = config.dedupe_ttl_ms or DEDUPE_TTL_MS
self._lock_scope_config = config.lock_scope
self._on_lock_conflict: OnLockConflict | None = config.on_lock_conflict
# -- Concurrency config -----------------------------------------------
concurrency = config.concurrency
if concurrency is None:
self._concurrency_strategy: ConcurrencyStrategy = "drop"
self._concurrency_debounce_ms = 1500
self._concurrency_max_concurrent: int | None = None
self._concurrency_max_queue_size = 10
self._concurrency_on_queue_full: str = "drop-oldest"
self._concurrency_queue_entry_ttl_ms = 90_000
elif isinstance(concurrency, str):
self._concurrency_strategy = concurrency
self._concurrency_debounce_ms = 1500
self._concurrency_max_concurrent = None
self._concurrency_max_queue_size = 10
self._concurrency_on_queue_full = "drop-oldest"
self._concurrency_queue_entry_ttl_ms = 90_000
else:
# ConcurrencyConfig dataclass
self._concurrency_strategy = concurrency.strategy
self._concurrency_debounce_ms = concurrency.debounce_ms
self._concurrency_max_concurrent = concurrency.max_concurrent
self._concurrency_max_queue_size = concurrency.max_queue_size
self._concurrency_on_queue_full = concurrency.on_queue_full
self._concurrency_queue_entry_ttl_ms = concurrency.queue_entry_ttl_ms
# -- Message history (placeholder -- real impl would use MessageHistoryCache)
self._message_history = _MessageHistoryCache(self._state_adapter, config.message_history)
# -- Logger -----------------------------------------------------------
if isinstance(config.logger, str):
self._logger: Logger = ConsoleLogger(config.logger)
elif config.logger is not None:
self._logger = config.logger
else:
self._logger = ConsoleLogger("info")
# -- Handler registries -----------------------------------------------
self._mention_handlers: list[MentionHandler] = []
self._direct_message_handlers: list[DirectMessageHandler] = []
self._message_patterns: list[_MessagePattern] = []
self._subscribed_message_handlers: list[SubscribedMessageHandler] = []
self._reaction_handlers: list[_ReactionPattern] = []
self._action_handlers: list[_ActionPattern] = []
self._modal_submit_handlers: list[_ModalSubmitPattern] = []
self._modal_close_handlers: list[_ModalClosePattern] = []
self._slash_command_handlers: list[_SlashCommandPattern] = []
self._assistant_thread_started_handlers: list[AssistantThreadStartedHandler] = []
self._assistant_context_changed_handlers: list[AssistantContextChangedHandler] = []
self._app_home_opened_handlers: list[AppHomeOpenedHandler] = []
self._member_joined_channel_handlers: list[MemberJoinedChannelHandler] = []
# -- Init state -------------------------------------------------------
self._init_promise: asyncio.Task[None] | None = None
self._initialized = False
self._init_lock = asyncio.Lock()
# -- Cached mention regex patterns (populated lazily) ----------------
self._mention_patterns: dict[str, re.Pattern[str]] = {}
# -- Register adapters and build webhooks map --------------------------
self.webhooks: dict[str, Callable[..., Awaitable[Any]]] = {}
for name, adapter in config.adapters.items():
self._adapters[name] = adapter
# Capture name in closure
self.webhooks[name] = self._make_webhook_handler(name)
self._logger.debug("Chat instance created", {"adapters": list(config.adapters.keys())})
# ========================================================================
# Singleton management
# ========================================================================
def register_singleton(self) -> Chat:
"""Register this Chat instance as the global singleton.
Required for Thread/Channel deserialization without explicit adapter refs.
"""
set_chat_singleton(self) # type: ignore[arg-type]
return self
@staticmethod
def get_singleton() -> Chat:
"""Get the registered singleton Chat instance."""
return get_chat_singleton() # type: ignore[return-value]
@staticmethod
def has_singleton() -> bool:
return has_chat_singleton()
# ========================================================================
# ChatInstance protocol implementation
# ========================================================================
def get_adapter(self, name: str) -> Adapter | None:
return self._adapters.get(name)
def get_state(self) -> StateAdapter:
return self._state_adapter
def get_user_name(self) -> str:
return self._user_name
def get_logger(self, prefix: str | None = None) -> Logger:
if prefix:
return self._logger.child(prefix)
return self._logger
# ========================================================================
# Webhook routing
# ========================================================================
def _make_webhook_handler(self, adapter_name: str) -> Callable[..., Awaitable[Any]]:
async def handler(request: Any, options: WebhookOptions | None = None) -> Any:
return await self._handle_webhook(adapter_name, request, options)
return handler
async def _handle_webhook(
self,
adapter_name: str,
request: Any,
options: WebhookOptions | None = None,
) -> Any:
"""Handle a webhook request for a specific adapter."""
await self._ensure_initialized()
adapter = self._adapters.get(adapter_name)
if adapter is None:
raise ChatError(f"Unknown adapter: {adapter_name}")
return await adapter.handle_webhook(request, options)
# ========================================================================
# Initialization
# ========================================================================
async def _ensure_initialized(self) -> None:
if self._initialized:
return
async with self._init_lock:
if self._initialized:
return
if self._init_promise is None:
self._init_promise = asyncio.get_running_loop().create_task(self._do_initialize())
try:
await self._init_promise
except Exception:
# Reset so a subsequent call can retry initialization.
self._init_promise = None
raise
async def _do_initialize(self) -> None:
self._logger.info("Initializing chat instance...")
await self._state_adapter.connect()
self._logger.debug("State connected")
init_tasks = []
for adapter in self._adapters.values():
self._logger.debug("Initializing adapter", adapter.name)
init_tasks.append(adapter.initialize(self)) # type: ignore[arg-type]
await asyncio.gather(*init_tasks)
self._initialized = True
self._logger.info(
"Chat instance initialized",
{"adapters": list(self._adapters.keys())},
)
async def initialize(self) -> None:
"""Manually trigger initialization (automatic on first webhook)."""
await self._ensure_initialized()
async def shutdown(self) -> None:
"""Gracefully shut down all adapters and state."""
self._logger.info("Shutting down chat instance...")
tasks = []
for adapter in self._adapters.values():
if hasattr(adapter, "disconnect") and adapter.disconnect: # type: ignore[union-attr]
tasks.append(adapter.disconnect()) # type: ignore[union-attr]
results = await asyncio.gather(*tasks, return_exceptions=True)
for r in results:
if isinstance(r, Exception):
self._logger.error("Adapter disconnect failed", str(r))
await self._state_adapter.disconnect()
self._initialized = False
self._init_promise = None
self._logger.info("Chat instance shut down")
# ========================================================================
# Handler registration (decorator-style)
# ========================================================================
def on_mention(self, handler: MentionHandler) -> MentionHandler:
"""Register a handler for new @-mentions of the bot in unsubscribed threads.
Can be used as a decorator::
@chat.on_mention
async def handle(thread, message):
await thread.post("Hi!")
"""
self._mention_handlers.append(handler)
self._logger.debug("Registered mention handler")
return handler
def on_direct_message(self, handler: DirectMessageHandler) -> DirectMessageHandler:
"""Register a handler for direct messages."""
self._direct_message_handlers.append(handler)
self._logger.debug("Registered direct message handler")
return handler
def on_message(
self,
pattern: re.Pattern[str] | str,
) -> Callable[[MessageHandler], MessageHandler]:
"""Register a handler for messages matching a regex pattern.
Usage::
@chat.on_message(r"^!help")
async def handle(thread, message):
await thread.post("Help!")
"""
compiled = re.compile(pattern) if isinstance(pattern, str) else pattern
def decorator(handler: MessageHandler) -> MessageHandler:
self._message_patterns.append(_MessagePattern(compiled, handler))
self._logger.debug("Registered message pattern handler", {"pattern": str(compiled.pattern)})
return handler
return decorator
def on_subscribed_message(self, handler: SubscribedMessageHandler) -> SubscribedMessageHandler:
"""Register a handler for messages in subscribed threads."""
self._subscribed_message_handlers.append(handler)
self._logger.debug("Registered subscribed message handler")
return handler
# -- Reactions ---
def on_reaction(
self,
emoji_or_handler: list[EmojiFilter] | ReactionHandler | None = None,
handler: ReactionHandler | None = None,
) -> ReactionHandler | Callable[[ReactionHandler], ReactionHandler]:
"""Register a handler for reaction events.
Overloaded:
- ``chat.on_reaction(handler)`` -- all reactions
- ``chat.on_reaction([emoji_list], handler)``
- ``@chat.on_reaction()`` or ``@chat.on_reaction([emoji_list])`` as decorator
"""
if callable(emoji_or_handler) and handler is None:
# on_reaction(handler) -- no filter
self._reaction_handlers.append(_ReactionPattern([], emoji_or_handler))
self._logger.debug("Registered reaction handler for all emoji")
return emoji_or_handler
if isinstance(emoji_or_handler, list) and handler is not None:
# on_reaction([emoji], handler)
self._reaction_handlers.append(_ReactionPattern(emoji_or_handler, handler))
self._logger.debug("Registered reaction handler", {"emoji": [str(e) for e in emoji_or_handler]})
return handler
# Decorator form: @chat.on_reaction() or @chat.on_reaction([emoji])
emoji_list = emoji_or_handler if isinstance(emoji_or_handler, list) else []
def decorator(h: ReactionHandler) -> ReactionHandler:
self._reaction_handlers.append(_ReactionPattern(emoji_list, h))
return h
return decorator
# -- Actions ---
def on_action(
self,
action_ids_or_handler: str | list[str] | ActionHandler | None = None,
handler: ActionHandler | None = None,
) -> ActionHandler | Callable[[ActionHandler], ActionHandler]:
"""Register a handler for action events (button clicks in cards).
Overloaded:
- ``chat.on_action(handler)`` -- all actions
- ``chat.on_action("id", handler)``
- ``chat.on_action(["id1", "id2"], handler)``
- Decorator: ``@chat.on_action("id")``
"""
if callable(action_ids_or_handler) and handler is None:
self._action_handlers.append(_ActionPattern([], action_ids_or_handler))
self._logger.debug("Registered action handler for all actions")
return action_ids_or_handler
if isinstance(action_ids_or_handler, (str, list)) and handler is not None:
ids = [action_ids_or_handler] if isinstance(action_ids_or_handler, str) else action_ids_or_handler
self._action_handlers.append(_ActionPattern(ids, handler))
self._logger.debug("Registered action handler", {"action_ids": ids})
return handler
# Decorator form
ids = (
[action_ids_or_handler]
if isinstance(action_ids_or_handler, str)
else (action_ids_or_handler if isinstance(action_ids_or_handler, list) else [])
)
def decorator(h: ActionHandler) -> ActionHandler:
self._action_handlers.append(_ActionPattern(ids, h))
return h
return decorator
# -- Modal submit ---
def on_modal_submit(
self,
callback_ids_or_handler: str | list[str] | ModalSubmitHandler | None = None,
handler: ModalSubmitHandler | None = None,
) -> ModalSubmitHandler | Callable[[ModalSubmitHandler], ModalSubmitHandler]:
"""Register a handler for modal form submissions."""
if callable(callback_ids_or_handler) and handler is None:
self._modal_submit_handlers.append(_ModalSubmitPattern([], callback_ids_or_handler))
self._logger.debug("Registered modal submit handler for all modals")
return callback_ids_or_handler
if isinstance(callback_ids_or_handler, (str, list)) and handler is not None:
ids = [callback_ids_or_handler] if isinstance(callback_ids_or_handler, str) else callback_ids_or_handler
self._modal_submit_handlers.append(_ModalSubmitPattern(ids, handler))
self._logger.debug("Registered modal submit handler", {"callback_ids": ids})
return handler
ids = (
[callback_ids_or_handler]
if isinstance(callback_ids_or_handler, str)
else (callback_ids_or_handler if isinstance(callback_ids_or_handler, list) else [])
)
def decorator(h: ModalSubmitHandler) -> ModalSubmitHandler:
self._modal_submit_handlers.append(_ModalSubmitPattern(ids, h))
return h
return decorator
# -- Modal close ---
def on_modal_close(
self,
callback_ids_or_handler: str | list[str] | ModalCloseHandler | None = None,
handler: ModalCloseHandler | None = None,
) -> ModalCloseHandler | Callable[[ModalCloseHandler], ModalCloseHandler]:
"""Register a handler for modal close events."""
if callable(callback_ids_or_handler) and handler is None:
self._modal_close_handlers.append(_ModalClosePattern([], callback_ids_or_handler))
self._logger.debug("Registered modal close handler for all modals")
return callback_ids_or_handler
if isinstance(callback_ids_or_handler, (str, list)) and handler is not None:
ids = [callback_ids_or_handler] if isinstance(callback_ids_or_handler, str) else callback_ids_or_handler
self._modal_close_handlers.append(_ModalClosePattern(ids, handler))
self._logger.debug("Registered modal close handler", {"callback_ids": ids})
return handler
ids = (
[callback_ids_or_handler]
if isinstance(callback_ids_or_handler, str)
else (callback_ids_or_handler if isinstance(callback_ids_or_handler, list) else [])
)
def decorator(h: ModalCloseHandler) -> ModalCloseHandler:
self._modal_close_handlers.append(_ModalClosePattern(ids, h))
return h
return decorator
# -- Slash commands ---
def on_slash_command(
self,
commands_or_handler: str | list[str] | SlashCommandHandler | None = None,
handler: SlashCommandHandler | None = None,
) -> SlashCommandHandler | Callable[[SlashCommandHandler], SlashCommandHandler]:
"""Register a handler for slash command events.
Usage::
@chat.on_slash_command("/help")
async def handle(event):
await event.channel.post("Help!")
@chat.on_slash_command(["/status", "/health"])
async def handle(event):
await event.channel.post("OK")
# Catch-all
@chat.on_slash_command
async def handle(event):
pass
"""
if callable(commands_or_handler) and handler is None:
self._slash_command_handlers.append(_SlashCommandPattern([], commands_or_handler))
self._logger.debug("Registered slash command handler for all commands")
return commands_or_handler
if isinstance(commands_or_handler, (str, list)) and handler is not None:
cmds = [commands_or_handler] if isinstance(commands_or_handler, str) else commands_or_handler
normalized = [c if c.startswith("/") else f"/{c}" for c in cmds]
self._slash_command_handlers.append(_SlashCommandPattern(normalized, handler))
self._logger.debug("Registered slash command handler", {"commands": normalized})
return handler
# Decorator form
cmds_raw = (
[commands_or_handler]
if isinstance(commands_or_handler, str)
else (commands_or_handler if isinstance(commands_or_handler, list) else [])
)
normalized = [c if c.startswith("/") else f"/{c}" for c in cmds_raw] if cmds_raw else []
def decorator(h: SlashCommandHandler) -> SlashCommandHandler:
self._slash_command_handlers.append(_SlashCommandPattern(normalized, h))
return h
return decorator
# -- Assistant events ---
def on_assistant_thread_started(self, handler: AssistantThreadStartedHandler) -> AssistantThreadStartedHandler:
self._assistant_thread_started_handlers.append(handler)
self._logger.debug("Registered assistant thread started handler")
return handler
def on_assistant_context_changed(self, handler: AssistantContextChangedHandler) -> AssistantContextChangedHandler:
self._assistant_context_changed_handlers.append(handler)
self._logger.debug("Registered assistant context changed handler")
return handler
def on_app_home_opened(self, handler: AppHomeOpenedHandler) -> AppHomeOpenedHandler:
self._app_home_opened_handlers.append(handler)
self._logger.debug("Registered app home opened handler")
return handler
def on_member_joined_channel(self, handler: MemberJoinedChannelHandler) -> MemberJoinedChannelHandler:
self._member_joined_channel_handlers.append(handler)
self._logger.debug("Registered member joined channel handler")
return handler
# ========================================================================
# Adapter lookup
# ========================================================================
def get_adapter_by_name(self, name: str) -> Adapter | None:
"""Get an adapter by name."""
return self._adapters.get(name)
# ========================================================================
# JSON reviver
# ========================================================================
def reviver(self) -> Callable[[str, Any], Any]:
"""Return a JSON reviver that deserializes Thread/Channel/Message objects.
Ensures this Chat instance is the registered singleton.
"""
self.register_singleton()
def _reviver(key: str, value: Any) -> Any:
if isinstance(value, dict) and "_type" in value:
t = value["_type"]
if t == "chat:Thread":
return ThreadImpl.from_json(value)
if t == "chat:Channel":
return ChannelImpl.from_json(value)
if t == "chat:Message":
return _message_from_json(value)
return value
return _reviver
# ========================================================================
# Process* methods (called by adapters)
# ========================================================================
def process_message(
self,
adapter: Adapter,
thread_id: str,
message_or_factory: Message | Callable[[], Awaitable[Message]],
options: WebhookOptions | None = None,
) -> None:
"""Process an incoming message from an adapter.
Handles waitUntil registration and error catching.
"""
async def _task() -> None:
msg = await message_or_factory() if callable(message_or_factory) else message_or_factory
await self.handle_incoming_message(adapter, thread_id, msg)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error(
"Message processing error", {"thread_id": thread_id, "error": str(t.exception())}
)
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_reaction(
self,
event: ReactionEvent,
options: WebhookOptions | None = None,
) -> None:
"""Process an incoming reaction event."""
task = _create_task(self._handle_reaction_event(event))
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Reaction processing error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_action(
self,
event: ActionEvent,
options: WebhookOptions | None = None,
) -> None:
"""Process an incoming action event (button click)."""
task = _create_task(self._handle_action_event(event))
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Action processing error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
async def process_modal_submit(
self,
event: ModalSubmitEvent,
context_id: str | None = None,
options: WebhookOptions | None = None,
) -> ModalResponse | None:
"""Process a modal form submission. Returns optional response."""
related = await self._retrieve_modal_context(event.adapter.name, context_id)
full_event = ModalSubmitEvent(
adapter=event.adapter,
user=event.user,
view_id=event.view_id,
callback_id=event.callback_id,
values=event.values,
private_metadata=event.private_metadata,
related_thread=related.get("related_thread"),
related_message=related.get("related_message"),
related_channel=related.get("related_channel"),
raw=event.raw,
)
for pat in self._modal_submit_handlers:
if not pat.callback_ids or event.callback_id in pat.callback_ids:
try:
response = await pat.handler(full_event)
if response is not None:
return response
except Exception as exc:
self._logger.error(
"Modal submit handler error",
{"callback_id": event.callback_id, "error": str(exc)},
)
return None
def process_modal_close(
self,
event: ModalCloseEvent,
context_id: str | None = None,
options: WebhookOptions | None = None,
) -> None:
"""Process a modal close event."""
async def _task() -> None:
related = await self._retrieve_modal_context(event.adapter.name, context_id)
full_event = ModalCloseEvent(
adapter=event.adapter,
user=event.user,
view_id=event.view_id,
callback_id=event.callback_id,
private_metadata=event.private_metadata,
related_thread=related.get("related_thread"),
related_message=related.get("related_message"),
related_channel=related.get("related_channel"),
raw=event.raw,
)
for pat in self._modal_close_handlers:
if not pat.callback_ids or event.callback_id in pat.callback_ids:
await pat.handler(full_event)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Modal close handler error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_slash_command(
self,
event: SlashCommandEvent,
options: WebhookOptions | None = None,
) -> None:
"""Process a slash command event."""
task = _create_task(self._handle_slash_command_event(event))
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Slash command processing error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_assistant_thread_started(
self,
event: AssistantThreadStartedEvent,
options: WebhookOptions | None = None,
) -> None:
async def _task() -> None:
for h in self._assistant_thread_started_handlers:
await h(event)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Assistant thread started handler error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_assistant_context_changed(
self,
event: AssistantContextChangedEvent,
options: WebhookOptions | None = None,
) -> None:
async def _task() -> None:
for h in self._assistant_context_changed_handlers:
await h(event)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Assistant context changed handler error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_app_home_opened(
self,
event: AppHomeOpenedEvent,
options: WebhookOptions | None = None,
) -> None:
async def _task() -> None:
for h in self._app_home_opened_handlers:
await h(event)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("App home opened handler error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
def process_member_joined_channel(
self,
event: MemberJoinedChannelEvent,
options: WebhookOptions | None = None,
) -> None:
async def _task() -> None:
for h in self._member_joined_channel_handlers:
await h(event)
task = _create_task(_task())
if task is not None:
task.add_done_callback(
lambda t: (
self._logger.error("Member joined channel handler error", {"error": str(t.exception())})
if not t.cancelled() and t.exception()
else None
)
)
if options and options.wait_until:
options.wait_until(task)
# ========================================================================
# Slash command handling
# ========================================================================
async def _handle_slash_command_event(self, event: SlashCommandEvent) -> None:
self._logger.debug(
"Incoming slash command",
{
"adapter": event.adapter.name,
"command": event.command,
"text": event.text,
"user": event.user.user_name,
},
)
if event.user.is_me:
self._logger.debug("Skipping slash command from self")
return
# Create channel for the command
channel_id = getattr(event, "channel_id", None) or (event.channel.id if event.channel else "")
channel = ChannelImpl(
_ChannelImplConfigForChat(
id=channel_id,
adapter=event.adapter,
state_adapter=self._state_adapter,
)
)
# Build openModal helper
async def _open_modal(modal: Any) -> dict[str, str] | None:
trigger_id = event.trigger_id
if not trigger_id:
self._logger.warn("Cannot open modal: no trigger_id available")
return None
if not hasattr(event.adapter, "open_modal") or not event.adapter.open_modal: # type: ignore[union-attr]
self._logger.warn(f"Cannot open modal: {event.adapter.name} does not support modals")
return None
context_id = str(uuid.uuid4())
self._store_modal_context(event.adapter.name, context_id, channel=channel)
return await event.adapter.open_modal(trigger_id, modal, context_id) # type: ignore[union-attr]
full_event = SlashCommandEvent(