-
Notifications
You must be signed in to change notification settings - Fork 288
Expand file tree
/
Copy pathassistant.py
More file actions
302 lines (267 loc) · 11.5 KB
/
assistant.py
File metadata and controls
302 lines (267 loc) · 11.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
import logging
from functools import wraps
from logging import Logger
from typing import List, Optional, Union, Callable
from slack_bolt.context.save_thread_context import SaveThreadContext
from slack_bolt.context.assistant.thread_context_store.store import AssistantThreadContextStore
from slack_bolt.listener_matcher.builtins import build_listener_matcher
from slack_bolt.middleware.attaching_agent_kwargs import AttachingAgentKwargs
from slack_bolt.request.request import BoltRequest
from slack_bolt.response.response import BoltResponse
from slack_bolt.listener_matcher import CustomListenerMatcher
from slack_bolt.error import BoltError
from slack_bolt.listener.custom_listener import CustomListener
from slack_bolt.listener import Listener
from slack_bolt.listener.thread_runner import ThreadListenerRunner
from slack_bolt.middleware import Middleware
from slack_bolt.listener_matcher import ListenerMatcher
from slack_bolt.request.payload_utils import (
is_assistant_thread_started_event,
is_user_message_event_in_assistant_thread,
is_assistant_thread_context_changed_event,
is_other_message_sub_event_in_assistant_thread,
is_bot_message_event_in_assistant_thread,
)
from slack_bolt.util.utils import is_used_without_argument
class Assistant(Middleware):
_thread_started_listeners: Optional[List[Listener]]
_thread_context_changed_listeners: Optional[List[Listener]]
_user_message_listeners: Optional[List[Listener]]
_bot_message_listeners: Optional[List[Listener]]
thread_context_store: Optional[AssistantThreadContextStore]
base_logger: Optional[logging.Logger]
def __init__(
self,
*,
app_name: str = "assistant",
thread_context_store: Optional[AssistantThreadContextStore] = None,
logger: Optional[logging.Logger] = None,
):
self.app_name = app_name
self.thread_context_store = thread_context_store
self.base_logger = logger
self._thread_started_listeners = None
self._thread_context_changed_listeners = None
self._user_message_listeners = None
self._bot_message_listeners = None
def thread_started(
self,
*args,
matchers: Optional[Union[Callable[..., bool], ListenerMatcher]] = None,
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
if self._thread_started_listeners is None:
self._thread_started_listeners = []
all_matchers = self._merge_matchers(is_assistant_thread_started_event, matchers)
if is_used_without_argument(args):
func = args[0]
self._thread_started_listeners.append(
self.build_listener(
listener_or_functions=func,
matchers=all_matchers,
middleware=middleware, # type:ignore[arg-type]
)
)
return func
def _inner(func):
functions = [func] + (lazy if lazy is not None else [])
self._thread_started_listeners.append(
self.build_listener(
listener_or_functions=functions,
matchers=all_matchers,
middleware=middleware,
)
)
@wraps(func)
def _wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _wrapper
return _inner
def user_message(
self,
*args,
matchers: Optional[Union[Callable[..., bool], ListenerMatcher]] = None,
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
if self._user_message_listeners is None:
self._user_message_listeners = []
all_matchers = self._merge_matchers(is_user_message_event_in_assistant_thread, matchers)
if is_used_without_argument(args):
func = args[0]
self._user_message_listeners.append(
self.build_listener(
listener_or_functions=func,
matchers=all_matchers,
middleware=middleware, # type:ignore[arg-type]
)
)
return func
def _inner(func):
functions = [func] + (lazy if lazy is not None else [])
self._user_message_listeners.append(
self.build_listener(
listener_or_functions=functions,
matchers=all_matchers,
middleware=middleware,
)
)
@wraps(func)
def _wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _wrapper
return _inner
def bot_message(
self,
*args,
matchers: Optional[Union[Callable[..., bool], ListenerMatcher]] = None,
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
if self._bot_message_listeners is None:
self._bot_message_listeners = []
all_matchers = self._merge_matchers(is_bot_message_event_in_assistant_thread, matchers)
if is_used_without_argument(args):
func = args[0]
self._bot_message_listeners.append(
self.build_listener(
listener_or_functions=func,
matchers=all_matchers,
middleware=middleware, # type:ignore[arg-type]
)
)
return func
def _inner(func):
functions = [func] + (lazy if lazy is not None else [])
self._bot_message_listeners.append(
self.build_listener(
listener_or_functions=functions,
matchers=all_matchers,
middleware=middleware,
)
)
@wraps(func)
def _wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _wrapper
return _inner
def thread_context_changed(
self,
*args,
matchers: Optional[Union[Callable[..., bool], ListenerMatcher]] = None,
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
if self._thread_context_changed_listeners is None:
self._thread_context_changed_listeners = []
all_matchers = self._merge_matchers(is_assistant_thread_context_changed_event, matchers)
if is_used_without_argument(args):
func = args[0]
self._thread_context_changed_listeners.append(
self.build_listener(
listener_or_functions=func,
matchers=all_matchers,
middleware=middleware, # type:ignore[arg-type]
)
)
return func
def _inner(func):
functions = [func] + (lazy if lazy is not None else [])
self._thread_context_changed_listeners.append(
self.build_listener(
listener_or_functions=functions,
matchers=all_matchers,
middleware=middleware,
)
)
@wraps(func)
def _wrapper(*args, **kwargs):
return func(*args, **kwargs)
return _wrapper
return _inner
def _merge_matchers(
self,
primary_matcher: Callable[..., bool],
custom_matchers: Optional[Union[Callable[..., bool], ListenerMatcher]],
):
return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + (
custom_matchers or []
) # type:ignore[operator]
@staticmethod
def default_thread_context_changed(save_thread_context: SaveThreadContext, payload: dict):
save_thread_context(payload["assistant_thread"]["context"])
def process( # type:ignore[return]
self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]
) -> Optional[BoltResponse]:
if self._thread_context_changed_listeners is None:
self.thread_context_changed(self.default_thread_context_changed)
listener_runner: ThreadListenerRunner = req.context.listener_runner
for listeners in [
self._thread_started_listeners,
self._thread_context_changed_listeners,
self._user_message_listeners,
self._bot_message_listeners,
]:
if listeners is not None:
for listener in listeners:
if listener.matches(req=req, resp=resp):
middleware_resp, next_was_not_called = listener.run_middleware(req=req, resp=resp)
if next_was_not_called:
if middleware_resp is not None:
return middleware_resp
# The listener middleware didn't call next().
# This means the listener is not for this incoming request.
continue
if middleware_resp is not None:
resp = middleware_resp
return listener_runner.run(
request=req,
response=resp,
listener_name="assistant_listener",
listener=listener,
)
if is_other_message_sub_event_in_assistant_thread(req.body):
# message_changed, message_deleted, etc.
return req.context.ack()
next()
def build_listener(
self,
listener_or_functions: Union[Listener, Callable, List[Callable]],
matchers: Optional[List[Union[ListenerMatcher, Callable[..., bool]]]] = None,
middleware: Optional[List[Middleware]] = None,
base_logger: Optional[Logger] = None,
) -> Listener:
if isinstance(listener_or_functions, Callable): # type:ignore[arg-type]
listener_or_functions = [listener_or_functions] # type:ignore[list-item]
if isinstance(listener_or_functions, Listener):
return listener_or_functions
elif isinstance(listener_or_functions, list):
middleware = middleware if middleware else []
middleware.insert(0, AttachingAgentKwargs(self.thread_context_store))
functions = listener_or_functions
ack_function = functions.pop(0)
matchers = matchers if matchers else []
listener_matchers: List[ListenerMatcher] = []
for matcher in matchers:
if isinstance(matcher, ListenerMatcher):
listener_matchers.append(matcher)
elif isinstance(matcher, Callable): # type:ignore[arg-type]
listener_matchers.append(
build_listener_matcher(
func=matcher,
asyncio=False,
base_logger=base_logger,
)
)
return CustomListener(
app_name=self.app_name,
matchers=listener_matchers,
middleware=middleware,
ack_function=ack_function,
lazy_functions=functions,
auto_acknowledgement=True,
base_logger=base_logger or self.base_logger,
)
else:
raise BoltError(f"Invalid listener: {type(listener_or_functions)} detected")