From 3f9d3761dba44a1c259055d56a046ba8e462a8c1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 10:34:37 -0400 Subject: [PATCH 1/7] chore(deps): bump codecov/codecov-action from 5.5.2 to 6.0.0 (#1475) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci-build.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 6c4cd5a6a..324ff7d80 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -126,7 +126,7 @@ jobs: pytest tests/scenario_tests_async/ --junitxml=reports/test_scenario_async.xml - name: Upload test results to Codecov if: ${{ !cancelled() }} - uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 with: directory: ./reports/ fail_ci_if_error: true @@ -162,7 +162,7 @@ jobs: run: | pytest --cov=./slack_bolt/ --cov-report=xml - name: Upload coverage to Codecov - uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2 + uses: codecov/codecov-action@57e3a136b779b570ffcdbf80b3bdc90e7fab3de2 # v6.0.0 with: fail_ci_if_error: true report_type: coverage From 13a6dff9d6682593982604e587b7340dcc2e9d60 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 10:39:18 -0400 Subject: [PATCH 2/7] chore(deps): bump slackapi/slack-github-action from 2.1.1 to 3.0.1 (#1476) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci-build.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci-build.yml b/.github/workflows/ci-build.yml index 324ff7d80..6d504ea83 100644 --- a/.github/workflows/ci-build.yml +++ b/.github/workflows/ci-build.yml @@ -179,7 +179,7 @@ jobs: if: ${{ !success() && github.ref == 'refs/heads/main' && github.event_name != 'workflow_dispatch' }} steps: - name: Send notifications of failing tests - uses: slackapi/slack-github-action@91efab103c0de0a537f72a35f6b8cda0ee76bf0a # v2.1.1 + uses: slackapi/slack-github-action@af78098f536edbc4de71162a307590698245be95 # v3.0.1 with: errors: true webhook: ${{ secrets.SLACK_REGRESSION_FAILURES_WEBHOOK_URL }} From dbe1590498a80903b5b5ce559b89c4640e84c775 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 2 Apr 2026 10:46:04 -0400 Subject: [PATCH 3/7] chore(deps): bump dependabot/fetch-metadata from 2.5.0 to 3.0.0 (#1477) Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/dependencies.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml index 824d57701..9666057aa 100644 --- a/.github/workflows/dependencies.yml +++ b/.github/workflows/dependencies.yml @@ -12,7 +12,7 @@ jobs: steps: - name: Collect metadata id: metadata - uses: dependabot/fetch-metadata@21025c705c08248db411dc16f3619e6b5f9ea21a # v2.5.0 + uses: dependabot/fetch-metadata@ffa630c65fa7e0ecfa0625b5ceda64399aea1b36 # v3.0.0 with: github-token: "${{ secrets.GITHUB_TOKEN }}" - name: Approve From 064ef2e83ad9035827e1267243ee56130e5b12fd Mon Sep 17 00:00:00 2001 From: William Bergamin Date: Mon, 6 Apr 2026 17:36:31 -0400 Subject: [PATCH 4/7] chore: remove experiment around say_stream (#1471) Co-authored-by: Eden Zimbelman --- .../context/say_stream/async_say_stream.py | 14 +------------ slack_bolt/context/say_stream/say_stream.py | 14 +------------ slack_bolt/warning/__init__.py | 7 ------- tests/slack_bolt/context/test_say_stream.py | 20 ++++-------------- .../context/test_async_say_stream.py | 21 ++++--------------- 5 files changed, 10 insertions(+), 66 deletions(-) delete mode 100644 slack_bolt/warning/__init__.py diff --git a/slack_bolt/context/say_stream/async_say_stream.py b/slack_bolt/context/say_stream/async_say_stream.py index dc752d02a..af776891b 100644 --- a/slack_bolt/context/say_stream/async_say_stream.py +++ b/slack_bolt/context/say_stream/async_say_stream.py @@ -1,11 +1,8 @@ -import warnings from typing import Optional from slack_sdk.web.async_client import AsyncWebClient from slack_sdk.web.async_chat_stream import AsyncChatStream -from slack_bolt.warning import ExperimentalWarning - class AsyncSayStream: client: AsyncWebClient @@ -39,16 +36,7 @@ async def __call__( thread_ts: Optional[str] = None, **kwargs, ) -> AsyncChatStream: - """Starts a new chat stream with context. - - Warning: This is an experimental feature and may change in future versions. - """ - warnings.warn( - "say_stream is experimental and may change in future versions.", - category=ExperimentalWarning, - stacklevel=2, - ) - + """Starts a new chat stream with context.""" channel = channel or self.channel thread_ts = thread_ts or self.thread_ts if channel is None: diff --git a/slack_bolt/context/say_stream/say_stream.py b/slack_bolt/context/say_stream/say_stream.py index 1e1d7985f..b6a5ca797 100644 --- a/slack_bolt/context/say_stream/say_stream.py +++ b/slack_bolt/context/say_stream/say_stream.py @@ -1,11 +1,8 @@ -import warnings from typing import Optional from slack_sdk import WebClient from slack_sdk.web.chat_stream import ChatStream -from slack_bolt.warning import ExperimentalWarning - class SayStream: client: WebClient @@ -39,16 +36,7 @@ def __call__( thread_ts: Optional[str] = None, **kwargs, ) -> ChatStream: - """Starts a new chat stream with context. - - Warning: This is an experimental feature and may change in future versions. - """ - warnings.warn( - "say_stream is experimental and may change in future versions.", - category=ExperimentalWarning, - stacklevel=2, - ) - + """Starts a new chat stream with context.""" channel = channel or self.channel thread_ts = thread_ts or self.thread_ts if channel is None: diff --git a/slack_bolt/warning/__init__.py b/slack_bolt/warning/__init__.py deleted file mode 100644 index 4991f4cd9..000000000 --- a/slack_bolt/warning/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -"""Bolt specific warning types.""" - - -class ExperimentalWarning(FutureWarning): - """Warning for features that are still in experimental phase.""" - - pass diff --git a/tests/slack_bolt/context/test_say_stream.py b/tests/slack_bolt/context/test_say_stream.py index c8f4c3a31..29d244a65 100644 --- a/tests/slack_bolt/context/test_say_stream.py +++ b/tests/slack_bolt/context/test_say_stream.py @@ -2,7 +2,6 @@ from slack_sdk import WebClient from slack_bolt.context.say_stream.say_stream import SayStream -from slack_bolt.warning import ExperimentalWarning from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server @@ -20,15 +19,13 @@ def teardown_method(self): def test_missing_channel_raises(self): say_stream = SayStream(client=self.web_client, channel=None, thread_ts="111.222") - with pytest.warns(ExperimentalWarning): - with pytest.raises(ValueError, match="channel"): - say_stream() + with pytest.raises(ValueError, match="channel"): + say_stream() def test_missing_thread_ts_raises(self): say_stream = SayStream(client=self.web_client, channel="C111", thread_ts=None) - with pytest.warns(ExperimentalWarning): - with pytest.raises(ValueError, match="thread_ts"): - say_stream() + with pytest.raises(ValueError, match="thread_ts"): + say_stream() def test_default_params(self): say_stream = SayStream( @@ -92,12 +89,3 @@ def test_buffer_size_overrides(self): "recipient_user_id": "U222", "task_display_mode": None, } - - def test_experimental_warning(self): - say_stream = SayStream( - client=self.web_client, - channel="C111", - thread_ts="111.222", - ) - with pytest.warns(ExperimentalWarning, match="say_stream is experimental"): - say_stream() diff --git a/tests/slack_bolt_async/context/test_async_say_stream.py b/tests/slack_bolt_async/context/test_async_say_stream.py index fbc4c5c7e..016549bd6 100644 --- a/tests/slack_bolt_async/context/test_async_say_stream.py +++ b/tests/slack_bolt_async/context/test_async_say_stream.py @@ -2,7 +2,6 @@ from slack_sdk.web.async_client import AsyncWebClient from slack_bolt.context.say_stream.async_say_stream import AsyncSayStream -from slack_bolt.warning import ExperimentalWarning from tests.mock_web_api_server import ( cleanup_mock_web_api_server, setup_mock_web_api_server, @@ -29,16 +28,14 @@ def setup_teardown(self): @pytest.mark.asyncio async def test_missing_channel_raises(self): say_stream = AsyncSayStream(client=self.web_client, channel=None, thread_ts="111.222") - with pytest.warns(ExperimentalWarning): - with pytest.raises(ValueError, match="channel"): - await say_stream() + with pytest.raises(ValueError, match="channel"): + await say_stream() @pytest.mark.asyncio async def test_missing_thread_ts_raises(self): say_stream = AsyncSayStream(client=self.web_client, channel="C111", thread_ts=None) - with pytest.warns(ExperimentalWarning): - with pytest.raises(ValueError, match="thread_ts"): - await say_stream() + with pytest.raises(ValueError, match="thread_ts"): + await say_stream() @pytest.mark.asyncio async def test_default_params(self): @@ -105,13 +102,3 @@ async def test_buffer_size_overrides(self): "recipient_user_id": "U222", "task_display_mode": None, } - - @pytest.mark.asyncio - async def test_experimental_warning(self): - say_stream = AsyncSayStream( - client=self.web_client, - channel="C111", - thread_ts="111.222", - ) - with pytest.warns(ExperimentalWarning, match="say_stream is experimental"): - await say_stream() From c64d69d2b64801602c849aa56e0ba2d4161e1f98 Mon Sep 17 00:00:00 2001 From: Eden Zimbelman Date: Mon, 6 Apr 2026 15:49:13 -0700 Subject: [PATCH 5/7] chore(release): version 1.28.0 (#1480) --- docs/reference/app/app.html | 30 ++- docs/reference/app/async_app.html | 34 ++- docs/reference/app/async_server.html | 6 +- docs/reference/app/index.html | 30 ++- docs/reference/async_app.html | 229 ++++++++++++++---- .../authorization/authorize_result.html | 4 +- docs/reference/authorization/index.html | 4 +- .../assistant/assistant_utilities.html | 14 ++ .../assistant/async_assistant_utilities.html | 14 ++ .../thread_context_store/file/index.html | 2 +- docs/reference/context/async_context.html | 25 +- docs/reference/context/base_context.html | 1 + docs/reference/context/context.html | 25 +- .../async_get_thread_context.html | 10 +- .../get_thread_context.html | 10 +- .../context/get_thread_context/index.html | 10 +- docs/reference/context/index.html | 30 ++- .../context/say_stream/async_say_stream.html | 174 +++++++++++++ docs/reference/context/say_stream/index.html | 191 +++++++++++++++ .../context/say_stream/say_stream.html | 174 +++++++++++++ docs/reference/error/index.html | 2 +- docs/reference/index.html | 212 +++++++++++++--- docs/reference/kwargs_injection/args.html | 11 +- .../kwargs_injection/async_args.html | 11 +- .../kwargs_injection/async_utils.html | 5 +- docs/reference/kwargs_injection/index.html | 16 +- docs/reference/kwargs_injection/utils.html | 5 +- .../async_listener_error_handler.html | 7 +- .../listener/listener_error_handler.html | 7 +- docs/reference/logger/messages.html | 4 +- .../middleware/assistant/assistant.html | 43 ++-- .../middleware/assistant/async_assistant.html | 59 +++-- .../reference/middleware/assistant/index.html | 43 ++-- docs/reference/middleware/async_builtins.html | 82 +++++++ .../middleware/async_middleware.html | 1 + .../async_middleware_error_handler.html | 7 +- .../async_attaching_conversation_kwargs.html | 155 ++++++++++++ .../attaching_conversation_kwargs.html | 149 ++++++++++++ .../attaching_conversation_kwargs/index.html | 166 +++++++++++++ docs/reference/middleware/index.html | 82 +++++++ docs/reference/middleware/middleware.html | 1 + .../middleware/middleware_error_handler.html | 7 +- .../oauth/async_callback_options.html | 4 +- .../reference/oauth/async_oauth_settings.html | 2 +- docs/reference/oauth/callback_options.html | 4 +- docs/reference/oauth/oauth_settings.html | 2 +- docs/reference/request/internals.html | 75 +++--- slack_bolt/version.py | 2 +- 48 files changed, 1868 insertions(+), 313 deletions(-) create mode 100644 docs/reference/context/say_stream/async_say_stream.html create mode 100644 docs/reference/context/say_stream/index.html create mode 100644 docs/reference/context/say_stream/say_stream.html create mode 100644 docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html create mode 100644 docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html create mode 100644 docs/reference/middleware/attaching_conversation_kwargs/index.html diff --git a/docs/reference/app/app.html b/docs/reference/app/app.html index c91d020ef..bf0d5ee00 100644 --- a/docs/reference/app/app.html +++ b/docs/reference/app/app.html @@ -48,7 +48,7 @@

Classes

class App -(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
token_verification_enabled: bool = True,
client: slack_sdk.web.client.WebClient | None = None,
before_authorize: Middleware | Callable[..., Any] | None = None,
authorize: Callable[..., AuthorizeResult] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: OAuthSettings | None = None,
oauth_flow: OAuthFlow | None = None,
verification_token: str | None = None,
listener_executor: concurrent.futures._base.Executor | None = None,
assistant_thread_context_store: AssistantThreadContextStore | None = None)
+(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
token_verification_enabled: bool = True,
client: slack_sdk.web.client.WebClient | None = None,
before_authorize: Middleware | Callable[..., Any] | None = None,
authorize: Callable[..., AuthorizeResult] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: OAuthSettings | None = None,
oauth_flow: OAuthFlow | None = None,
verification_token: str | None = None,
listener_executor: concurrent.futures._base.Executor | None = None,
assistant_thread_context_store: AssistantThreadContextStore | None = None,
attaching_conversation_kwargs_enabled: bool = True)
@@ -95,6 +95,7 @@

Classes

listener_executor: Optional[Executor] = None, # for AI Agents & Assistants assistant_thread_context_store: Optional[AssistantThreadContextStore] = None, + attaching_conversation_kwargs_enabled: bool = True, ): """Bolt App that provides functionalities to register middleware/listeners. @@ -315,6 +316,7 @@

Classes

listener_executor = ThreadPoolExecutor(max_workers=5) self._assistant_thread_context_store = assistant_thread_context_store + self._attaching_conversation_kwargs_enabled = attaching_conversation_kwargs_enabled self._process_before_response = process_before_response self._listener_runner = ThreadListenerRunner( @@ -799,10 +801,13 @@

Classes

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -860,6 +865,8 @@

Classes

primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -1356,20 +1363,6 @@

Classes

# It is intended for apps that start lazy listeners from their custom global middleware. req.context["listener_runner"] = self.listener_runner - # For AI Agents & Assistants - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=to_event(req.body), # type:ignore[arg-type] - context=req.context, - thread_context_store=self._assistant_thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_status"] = assistant.set_status - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context - @staticmethod def _to_listener_functions( kwargs: dict, @@ -1415,7 +1408,7 @@

Classes

CustomListener( app_name=self.name, ack_function=functions.pop(0), - lazy_functions=functions, # type:ignore[arg-type] + lazy_functions=functions, # type: ignore[arg-type] matchers=listener_matchers, middleware=listener_middleware, auto_acknowledgement=auto_acknowledgement, @@ -2203,10 +2196,13 @@

Args

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -2410,6 +2406,8 @@

Args

primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) diff --git a/docs/reference/app/async_app.html b/docs/reference/app/async_app.html index 9cbc801d0..cf4c651cb 100644 --- a/docs/reference/app/async_app.html +++ b/docs/reference/app/async_app.html @@ -48,7 +48,7 @@

Classes

class AsyncApp -(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
client: slack_sdk.web.async_client.AsyncWebClient | None = None,
before_authorize: AsyncMiddleware | Callable[..., Awaitable[Any]] | None = None,
authorize: Callable[..., Awaitable[AuthorizeResult]] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: AsyncOAuthSettings | None = None,
oauth_flow: AsyncOAuthFlow | None = None,
verification_token: str | None = None,
assistant_thread_context_store: AsyncAssistantThreadContextStore | None = None)
+(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
client: slack_sdk.web.async_client.AsyncWebClient | None = None,
before_authorize: AsyncMiddleware | Callable[..., Awaitable[Any]] | None = None,
authorize: Callable[..., Awaitable[AuthorizeResult]] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: AsyncOAuthSettings | None = None,
oauth_flow: AsyncOAuthFlow | None = None,
verification_token: str | None = None,
assistant_thread_context_store: AsyncAssistantThreadContextStore | None = None,
attaching_conversation_kwargs_enabled: bool = True)
@@ -92,6 +92,7 @@

Classes

verification_token: Optional[str] = None, # for AI Agents & Assistants assistant_thread_context_store: Optional[AsyncAssistantThreadContextStore] = None, + attaching_conversation_kwargs_enabled: bool = True, ): """Bolt App that provides functionalities to register middleware/listeners. @@ -312,6 +313,7 @@

Classes

self._async_listeners: List[AsyncListener] = [] self._assistant_thread_context_store = assistant_thread_context_store + self._attaching_conversation_kwargs_enabled = attaching_conversation_kwargs_enabled self._process_before_response = process_before_response self._async_listener_runner = AsyncioListenerRunner( @@ -565,7 +567,7 @@

Classes

self._framework_logger.debug(debug_checking_listener(listener_name)) if await listener.async_matches(req=req, resp=resp): # type: ignore[arg-type] # run all the middleware attached to this listener first - (middleware_resp, next_was_not_called) = await listener.run_async_middleware( + middleware_resp, next_was_not_called = await listener.run_async_middleware( req=req, resp=resp # type: ignore[arg-type] ) if next_was_not_called: @@ -815,10 +817,13 @@

Classes

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, True, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -879,6 +884,8 @@

Classes

asyncio=True, base_logger=self._base_logger, ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, AsyncMessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -1380,20 +1387,6 @@

Classes

# It is intended for apps that start lazy listeners from their custom global middleware. req.context["listener_runner"] = self.listener_runner - # For AI Agents & Assistants - if is_assistant_event(req.body): - assistant = AsyncAssistantUtilities( - payload=to_event(req.body), # type:ignore[arg-type] - context=req.context, - thread_context_store=self._assistant_thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_status"] = assistant.set_status - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context - @staticmethod def _to_listener_functions( kwargs: dict, @@ -1444,7 +1437,7 @@

Classes

AsyncCustomListener( app_name=self.name, ack_function=functions.pop(0), - lazy_functions=functions, # type:ignore[arg-type] + lazy_functions=functions, # type: ignore[arg-type] matchers=listener_matchers, middleware=listener_middleware, auto_acknowledgement=auto_acknowledgement, @@ -1794,7 +1787,7 @@

Args

self._framework_logger.debug(debug_checking_listener(listener_name)) if await listener.async_matches(req=req, resp=resp): # type: ignore[arg-type] # run all the middleware attached to this listener first - (middleware_resp, next_was_not_called) = await listener.run_async_middleware( + middleware_resp, next_was_not_called = await listener.run_async_middleware( req=req, resp=resp # type: ignore[arg-type] ) if next_was_not_called: @@ -2243,10 +2236,13 @@

Args

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, True, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -2454,6 +2450,8 @@

Args

asyncio=True, base_logger=self._base_logger, ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, AsyncMessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) diff --git a/docs/reference/app/async_server.html b/docs/reference/app/async_server.html index b95b8a2b3..5eefe90dd 100644 --- a/docs/reference/app/async_server.html +++ b/docs/reference/app/async_server.html @@ -59,14 +59,14 @@

Classes

port: int path: str host: str - bolt_app: "AsyncApp" # type: ignore[name-defined] + bolt_app: "AsyncApp" web_app: web.Application def __init__( self, port: int, path: str, - app: "AsyncApp", # type: ignore[name-defined] + app: "AsyncApp", host: Optional[str] = None, ): """Standalone AIOHTTP Web Server. @@ -81,7 +81,7 @@

Classes

self.port = port self.path = path self.host = host if host is not None else "0.0.0.0" - self.bolt_app: "AsyncApp" = app # type: ignore[name-defined] + self.bolt_app: "AsyncApp" = app self.web_app = web.Application() self._bolt_oauth_flow = self.bolt_app.oauth_flow if self._bolt_oauth_flow: diff --git a/docs/reference/app/index.html b/docs/reference/app/index.html index 8821e5af9..32e006944 100644 --- a/docs/reference/app/index.html +++ b/docs/reference/app/index.html @@ -67,7 +67,7 @@

Classes

class App -(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
token_verification_enabled: bool = True,
client: slack_sdk.web.client.WebClient | None = None,
before_authorize: Middleware | Callable[..., Any] | None = None,
authorize: Callable[..., AuthorizeResult] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: OAuthSettings | None = None,
oauth_flow: OAuthFlow | None = None,
verification_token: str | None = None,
listener_executor: concurrent.futures._base.Executor | None = None,
assistant_thread_context_store: AssistantThreadContextStore | None = None)
+(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
token_verification_enabled: bool = True,
client: slack_sdk.web.client.WebClient | None = None,
before_authorize: Middleware | Callable[..., Any] | None = None,
authorize: Callable[..., AuthorizeResult] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: OAuthSettings | None = None,
oauth_flow: OAuthFlow | None = None,
verification_token: str | None = None,
listener_executor: concurrent.futures._base.Executor | None = None,
assistant_thread_context_store: AssistantThreadContextStore | None = None,
attaching_conversation_kwargs_enabled: bool = True)
@@ -114,6 +114,7 @@

Classes

listener_executor: Optional[Executor] = None, # for AI Agents & Assistants assistant_thread_context_store: Optional[AssistantThreadContextStore] = None, + attaching_conversation_kwargs_enabled: bool = True, ): """Bolt App that provides functionalities to register middleware/listeners. @@ -334,6 +335,7 @@

Classes

listener_executor = ThreadPoolExecutor(max_workers=5) self._assistant_thread_context_store = assistant_thread_context_store + self._attaching_conversation_kwargs_enabled = attaching_conversation_kwargs_enabled self._process_before_response = process_before_response self._listener_runner = ThreadListenerRunner( @@ -818,10 +820,13 @@

Classes

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -879,6 +884,8 @@

Classes

primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -1375,20 +1382,6 @@

Classes

# It is intended for apps that start lazy listeners from their custom global middleware. req.context["listener_runner"] = self.listener_runner - # For AI Agents & Assistants - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=to_event(req.body), # type:ignore[arg-type] - context=req.context, - thread_context_store=self._assistant_thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_status"] = assistant.set_status - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context - @staticmethod def _to_listener_functions( kwargs: dict, @@ -1434,7 +1427,7 @@

Classes

CustomListener( app_name=self.name, ack_function=functions.pop(0), - lazy_functions=functions, # type:ignore[arg-type] + lazy_functions=functions, # type: ignore[arg-type] matchers=listener_matchers, middleware=listener_middleware, auto_acknowledgement=auto_acknowledgement, @@ -2222,10 +2215,13 @@

Args

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -2429,6 +2425,8 @@

Args

primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) diff --git a/docs/reference/async_app.html b/docs/reference/async_app.html index 8fd975be9..3494ec289 100644 --- a/docs/reference/async_app.html +++ b/docs/reference/async_app.html @@ -139,7 +139,7 @@

Class variables

class AsyncApp -(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
client: slack_sdk.web.async_client.AsyncWebClient | None = None,
before_authorize: AsyncMiddleware | Callable[..., Awaitable[Any]] | None = None,
authorize: Callable[..., Awaitable[AuthorizeResult]] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: AsyncOAuthSettings | None = None,
oauth_flow: AsyncOAuthFlow | None = None,
verification_token: str | None = None,
assistant_thread_context_store: AsyncAssistantThreadContextStore | None = None)
+(*,
logger: logging.Logger | None = None,
name: str | None = None,
process_before_response: bool = False,
raise_error_for_unhandled_request: bool = False,
signing_secret: str | None = None,
token: str | None = None,
client: slack_sdk.web.async_client.AsyncWebClient | None = None,
before_authorize: AsyncMiddleware | Callable[..., Awaitable[Any]] | None = None,
authorize: Callable[..., Awaitable[AuthorizeResult]] | None = None,
user_facing_authorize_error_message: str | None = None,
installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
installation_store_bot_only: bool | None = None,
request_verification_enabled: bool = True,
ignoring_self_events_enabled: bool = True,
ignoring_self_assistant_message_events_enabled: bool = True,
ssl_check_enabled: bool = True,
url_verification_enabled: bool = True,
attaching_function_token_enabled: bool = True,
oauth_settings: AsyncOAuthSettings | None = None,
oauth_flow: AsyncOAuthFlow | None = None,
verification_token: str | None = None,
assistant_thread_context_store: AsyncAssistantThreadContextStore | None = None,
attaching_conversation_kwargs_enabled: bool = True)
@@ -183,6 +183,7 @@

Class variables

verification_token: Optional[str] = None, # for AI Agents & Assistants assistant_thread_context_store: Optional[AsyncAssistantThreadContextStore] = None, + attaching_conversation_kwargs_enabled: bool = True, ): """Bolt App that provides functionalities to register middleware/listeners. @@ -403,6 +404,7 @@

Class variables

self._async_listeners: List[AsyncListener] = [] self._assistant_thread_context_store = assistant_thread_context_store + self._attaching_conversation_kwargs_enabled = attaching_conversation_kwargs_enabled self._process_before_response = process_before_response self._async_listener_runner = AsyncioListenerRunner( @@ -656,7 +658,7 @@

Class variables

self._framework_logger.debug(debug_checking_listener(listener_name)) if await listener.async_matches(req=req, resp=resp): # type: ignore[arg-type] # run all the middleware attached to this listener first - (middleware_resp, next_was_not_called) = await listener.run_async_middleware( + middleware_resp, next_was_not_called = await listener.run_async_middleware( req=req, resp=resp # type: ignore[arg-type] ) if next_was_not_called: @@ -906,10 +908,13 @@

Class variables

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, True, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -970,6 +975,8 @@

Class variables

asyncio=True, base_logger=self._base_logger, ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, AsyncMessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -1471,20 +1478,6 @@

Class variables

# It is intended for apps that start lazy listeners from their custom global middleware. req.context["listener_runner"] = self.listener_runner - # For AI Agents & Assistants - if is_assistant_event(req.body): - assistant = AsyncAssistantUtilities( - payload=to_event(req.body), # type:ignore[arg-type] - context=req.context, - thread_context_store=self._assistant_thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_status"] = assistant.set_status - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context - @staticmethod def _to_listener_functions( kwargs: dict, @@ -1535,7 +1528,7 @@

Class variables

AsyncCustomListener( app_name=self.name, ack_function=functions.pop(0), - lazy_functions=functions, # type:ignore[arg-type] + lazy_functions=functions, # type: ignore[arg-type] matchers=listener_matchers, middleware=listener_middleware, auto_acknowledgement=auto_acknowledgement, @@ -1885,7 +1878,7 @@

Args

self._framework_logger.debug(debug_checking_listener(listener_name)) if await listener.async_matches(req=req, resp=resp): # type: ignore[arg-type] # run all the middleware attached to this listener first - (middleware_resp, next_was_not_called) = await listener.run_async_middleware( + middleware_resp, next_was_not_called = await listener.run_async_middleware( req=req, resp=resp # type: ignore[arg-type] ) if next_was_not_called: @@ -2334,10 +2327,13 @@

Args

middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, True, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -2545,6 +2541,8 @@

Args

asyncio=True, base_logger=self._base_logger, ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AsyncAttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, AsyncMessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -3285,7 +3283,7 @@

Args

func=is_assistant_thread_started_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3294,7 +3292,7 @@

Args

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3331,7 +3329,7 @@

Args

func=is_user_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3340,7 +3338,7 @@

Args

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3377,7 +3375,7 @@

Args

func=is_bot_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3386,7 +3384,7 @@

Args

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3423,7 +3421,7 @@

Args

func=is_assistant_thread_context_changed_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3432,7 +3430,7 @@

Args

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3460,14 +3458,14 @@

Args

primary_matcher: Union[Callable[..., bool], AsyncListenerMatcher], custom_matchers: Optional[Union[Callable[..., bool], AsyncListenerMatcher]], ): - return [primary_matcher] + (custom_matchers or []) # type:ignore[operator] + return [primary_matcher] + (custom_matchers or []) # type: ignore[operator] @staticmethod async def default_thread_context_changed(save_thread_context: AsyncSaveThreadContext, payload: dict): new_context: dict = payload["assistant_thread"]["context"] await save_thread_context(new_context) - async def async_process( # type:ignore[return] + async def async_process( # type: ignore[return] self, *, req: AsyncBoltRequest, @@ -3487,6 +3485,15 @@

Args

if listeners is not None: for listener in listeners: if listener is not None and await listener.async_matches(req=req, resp=resp): + middleware_resp, next_was_not_called = await listener.run_async_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(). + # Skip this listener and try the next one. + continue + if middleware_resp is not None: + resp = middleware_resp return await listener_runner.run( request=req, response=resp, @@ -3506,13 +3513,14 @@

Args

middleware: Optional[List[AsyncMiddleware]] = None, base_logger: Optional[Logger] = None, ) -> AsyncListener: - 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, Callable): # type: ignore[arg-type] + listener_or_functions = [listener_or_functions] # type: ignore[list-item] if isinstance(listener_or_functions, AsyncListener): return listener_or_functions elif isinstance(listener_or_functions, list): middleware = middleware if middleware else [] + middleware.insert(0, AsyncAttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -3524,7 +3532,7 @@

Args

else: listener_matchers.append( build_listener_matcher( - func=matcher, # type:ignore[arg-type] + func=matcher, # type: ignore[arg-type] asyncio=True, base_logger=base_logger, ) @@ -3599,7 +3607,7 @@

Methods

func=is_bot_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3608,7 +3616,7 @@

Methods

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3648,13 +3656,14 @@

Methods

middleware: Optional[List[AsyncMiddleware]] = None, base_logger: Optional[Logger] = None, ) -> AsyncListener: - 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, Callable): # type: ignore[arg-type] + listener_or_functions = [listener_or_functions] # type: ignore[list-item] if isinstance(listener_or_functions, AsyncListener): return listener_or_functions elif isinstance(listener_or_functions, list): middleware = middleware if middleware else [] + middleware.insert(0, AsyncAttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -3666,7 +3675,7 @@

Methods

else: listener_matchers.append( build_listener_matcher( - func=matcher, # type:ignore[arg-type] + func=matcher, # type: ignore[arg-type] asyncio=True, base_logger=base_logger, ) @@ -3707,7 +3716,7 @@

Methods

func=is_assistant_thread_context_changed_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3716,7 +3725,7 @@

Methods

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3763,7 +3772,7 @@

Methods

func=is_assistant_thread_started_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3772,7 +3781,7 @@

Methods

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3819,7 +3828,7 @@

Methods

func=is_user_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -3828,7 +3837,7 @@

Methods

self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3898,7 +3907,7 @@

Inherited members

# The return type is intentionally string to avoid circular imports @property - def listener_runner(self) -> "AsyncioListenerRunner": # type: ignore[name-defined] + def listener_runner(self) -> "AsyncioListenerRunner": """The properly configured listener_runner that is available for middleware/listeners.""" return self["listener_runner"] @@ -3967,7 +3976,7 @@

Inherited members

Callable `say()` function """ if "say" not in self: - self["say"] = AsyncSay(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = AsyncSay(client=self.client, channel=self.channel_id) return self["say"] @property @@ -4060,6 +4069,10 @@

Inherited members

def get_thread_context(self) -> Optional[AsyncGetThreadContext]: return self.get("get_thread_context") + @property + def say_stream(self) -> Optional[AsyncSayStream]: + return self.get("say_stream") + @property def save_thread_context(self) -> Optional[AsyncSaveThreadContext]: return self.get("save_thread_context") @@ -4275,7 +4288,7 @@

Returns

Expand source code
@property
-def listener_runner(self) -> "AsyncioListenerRunner":  # type: ignore[name-defined]
+def listener_runner(self) -> "AsyncioListenerRunner":
     """The properly configured listener_runner that is available for middleware/listeners."""
     return self["listener_runner"]
@@ -4365,7 +4378,7 @@

Returns

Callable `say()` function """ if "say" not in self: - self["say"] = AsyncSay(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = AsyncSay(client=self.client, channel=self.channel_id) return self["say"]

say() function for this request.

@@ -4383,6 +4396,18 @@

Returns

Returns

Callable say() function

+
prop say_streamAsyncSayStream | None
+
+
+ +Expand source code + +
@property
+def say_stream(self) -> Optional[AsyncSayStream]:
+    return self.get("say_stream")
+
+
+
prop set_statusAsyncSetStatus | None
@@ -4742,14 +4767,10 @@

Inherited members

if self.thread_context_loaded is True: return self._thread_context - if self.payload.get("assistant_thread") is not None: + thread = self.payload.get("assistant_thread") + if isinstance(thread, dict) and thread.get("context", {}).get("channel_id") is not None: # assistant_thread_started - thread = self.payload["assistant_thread"] - self._thread_context = ( - AssistantThreadContext(thread["context"]) - if thread.get("context", {}).get("channel_id") is not None - else None - ) + self._thread_context = AssistantThreadContext(thread["context"]) # for this event, the context will never be changed self.thread_context_loaded = True elif self.payload.get("channel") is not None and self.payload.get("thread_ts") is not None: @@ -5231,6 +5252,97 @@

Class variables

+
+class AsyncSayStream +(*,
client: slack_sdk.web.async_client.AsyncWebClient,
channel: str | None = None,
recipient_team_id: str | None = None,
recipient_user_id: str | None = None,
thread_ts: str | None = None)
+
+
+
+ +Expand source code + +
class AsyncSayStream:
+    client: AsyncWebClient
+    channel: Optional[str]
+    recipient_team_id: Optional[str]
+    recipient_user_id: Optional[str]
+    thread_ts: Optional[str]
+
+    def __init__(
+        self,
+        *,
+        client: AsyncWebClient,
+        channel: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+    ):
+        self.client = client
+        self.channel = channel
+        self.recipient_team_id = recipient_team_id
+        self.recipient_user_id = recipient_user_id
+        self.thread_ts = thread_ts
+
+    async def __call__(
+        self,
+        *,
+        buffer_size: Optional[int] = None,
+        channel: Optional[str] = None,
+        recipient_team_id: Optional[str] = None,
+        recipient_user_id: Optional[str] = None,
+        thread_ts: Optional[str] = None,
+        **kwargs,
+    ) -> AsyncChatStream:
+        """Starts a new chat stream with context."""
+        channel = channel or self.channel
+        thread_ts = thread_ts or self.thread_ts
+        if channel is None:
+            raise ValueError("say_stream without channel here is unsupported")
+        if thread_ts is None:
+            raise ValueError("say_stream without thread_ts here is unsupported")
+
+        if buffer_size is not None:
+            return await self.client.chat_stream(
+                buffer_size=buffer_size,
+                channel=channel,
+                recipient_team_id=recipient_team_id or self.recipient_team_id,
+                recipient_user_id=recipient_user_id or self.recipient_user_id,
+                thread_ts=thread_ts,
+                **kwargs,
+            )
+        return await self.client.chat_stream(
+            channel=channel,
+            recipient_team_id=recipient_team_id or self.recipient_team_id,
+            recipient_user_id=recipient_user_id or self.recipient_user_id,
+            thread_ts=thread_ts,
+            **kwargs,
+        )
+
+
+

Class variables

+
+
var channel : str | None
+
+

The type of the None singleton.

+
+
var client : slack_sdk.web.async_client.AsyncWebClient
+
+

The type of the None singleton.

+
+
var recipient_team_id : str | None
+
+

The type of the None singleton.

+
+
var recipient_user_id : str | None
+
+

The type of the None singleton.

+
+
var thread_ts : str | None
+
+

The type of the None singleton.

+
+
+
class AsyncSetStatus (client: slack_sdk.web.async_client.AsyncWebClient,
channel_id: str,
thread_ts: str)
@@ -5485,6 +5597,7 @@

respond
  • save_thread_context
  • say
  • +
  • say_stream
  • set_status
  • set_suggested_prompts
  • set_title
  • @@ -5565,6 +5678,16 @@

    AsyncSayStream

    + + +
  • AsyncSetStatus

    • channel_id
    • diff --git a/docs/reference/authorization/authorize_result.html b/docs/reference/authorization/authorize_result.html index d53c5cd5c..6eac3724d 100644 --- a/docs/reference/authorization/authorize_result.html +++ b/docs/reference/authorization/authorize_result.html @@ -48,7 +48,7 @@

      Classes

      class AuthorizeResult -(*,
      enterprise_id: str | None,
      team_id: str | None,
      team: str | None = None,
      url: str | None = None,
      bot_user_id: str | None = None,
      bot_id: str | None = None,
      bot_token: str | None = None,
      bot_scopes: Sequence[str] | str | None = None,
      user_id: str | None = None,
      user: str | None = None,
      user_token: str | None = None,
      user_scopes: Sequence[str] | str | None = None)
      +(*,
      enterprise_id: str | None,
      team_id: str | None,
      team: str | None = None,
      url: str | None = None,
      bot_user_id: str | None = None,
      bot_id: str | None = None,
      bot_token: str | None = None,
      bot_scopes: str | Sequence[str] | None = None,
      user_id: str | None = None,
      user: str | None = None,
      user_token: str | None = None,
      user_scopes: str | Sequence[str] | None = None)
      @@ -246,7 +246,7 @@

      Class variables

      Static methods

      -def from_auth_test_response(*,
      bot_token: str | None = None,
      user_token: str | None = None,
      bot_scopes: Sequence[str] | str | None = None,
      user_scopes: Sequence[str] | str | None = None,
      auth_test_response: slack_sdk.web.slack_response.SlackResponse | AsyncSlackResponse,
      user_auth_test_response: slack_sdk.web.slack_response.SlackResponse | AsyncSlackResponse | None = None)
      +def from_auth_test_response(*,
      bot_token: str | None = None,
      user_token: str | None = None,
      bot_scopes: str | Sequence[str] | None = None,
      user_scopes: str | Sequence[str] | None = None,
      auth_test_response: slack_sdk.web.slack_response.SlackResponse | ForwardRef('AsyncSlackResponse'),
      user_auth_test_response: slack_sdk.web.slack_response.SlackResponse | ForwardRef('AsyncSlackResponse') | None = None)
      diff --git a/docs/reference/authorization/index.html b/docs/reference/authorization/index.html index 2fdd1f916..19de311df 100644 --- a/docs/reference/authorization/index.html +++ b/docs/reference/authorization/index.html @@ -75,7 +75,7 @@

      Classes

      class AuthorizeResult -(*,
      enterprise_id: str | None,
      team_id: str | None,
      team: str | None = None,
      url: str | None = None,
      bot_user_id: str | None = None,
      bot_id: str | None = None,
      bot_token: str | None = None,
      bot_scopes: Sequence[str] | str | None = None,
      user_id: str | None = None,
      user: str | None = None,
      user_token: str | None = None,
      user_scopes: Sequence[str] | str | None = None)
      +(*,
      enterprise_id: str | None,
      team_id: str | None,
      team: str | None = None,
      url: str | None = None,
      bot_user_id: str | None = None,
      bot_id: str | None = None,
      bot_token: str | None = None,
      bot_scopes: str | Sequence[str] | None = None,
      user_id: str | None = None,
      user: str | None = None,
      user_token: str | None = None,
      user_scopes: str | Sequence[str] | None = None)
      @@ -273,7 +273,7 @@

      Class variables

      Static methods

      -def from_auth_test_response(*,
      bot_token: str | None = None,
      user_token: str | None = None,
      bot_scopes: Sequence[str] | str | None = None,
      user_scopes: Sequence[str] | str | None = None,
      auth_test_response: slack_sdk.web.slack_response.SlackResponse | AsyncSlackResponse,
      user_auth_test_response: slack_sdk.web.slack_response.SlackResponse | AsyncSlackResponse | None = None)
      +def from_auth_test_response(*,
      bot_token: str | None = None,
      user_token: str | None = None,
      bot_scopes: str | Sequence[str] | None = None,
      user_scopes: str | Sequence[str] | None = None,
      auth_test_response: slack_sdk.web.slack_response.SlackResponse | ForwardRef('AsyncSlackResponse'),
      user_auth_test_response: slack_sdk.web.slack_response.SlackResponse | ForwardRef('AsyncSlackResponse') | None = None)
      diff --git a/docs/reference/context/assistant/assistant_utilities.html b/docs/reference/context/assistant/assistant_utilities.html index d446b3c02..40db52284 100644 --- a/docs/reference/context/assistant/assistant_utilities.html +++ b/docs/reference/context/assistant/assistant_utilities.html @@ -91,6 +91,13 @@

      Classes

      @property def set_status(self) -> SetStatus: + warnings.warn( + "AssistantUtilities.set_status is deprecated. " + "Use the set_status argument directly in your listener function " + "or access it via context.set_status instead.", + DeprecationWarning, + stacklevel=2, + ) return SetStatus(self.client, self.channel_id, self.thread_ts) @property @@ -205,6 +212,13 @@

      Instance variables

      @property
       def set_status(self) -> SetStatus:
      +    warnings.warn(
      +        "AssistantUtilities.set_status is deprecated. "
      +        "Use the set_status argument directly in your listener function "
      +        "or access it via context.set_status instead.",
      +        DeprecationWarning,
      +        stacklevel=2,
      +    )
           return SetStatus(self.client, self.channel_id, self.thread_ts)
      diff --git a/docs/reference/context/assistant/async_assistant_utilities.html b/docs/reference/context/assistant/async_assistant_utilities.html index fc3cbbe8b..fc77b80cb 100644 --- a/docs/reference/context/assistant/async_assistant_utilities.html +++ b/docs/reference/context/assistant/async_assistant_utilities.html @@ -91,6 +91,13 @@

      Classes

      @property def set_status(self) -> AsyncSetStatus: + warnings.warn( + "AsyncAssistantUtilities.set_status is deprecated. " + "Use the set_status argument directly in your listener function " + "or access it via context.set_status instead.", + DeprecationWarning, + stacklevel=2, + ) return AsyncSetStatus(self.client, self.channel_id, self.thread_ts) @property @@ -199,6 +206,13 @@

      Instance variables

      @property
       def set_status(self) -> AsyncSetStatus:
      +    warnings.warn(
      +        "AsyncAssistantUtilities.set_status is deprecated. "
      +        "Use the set_status argument directly in your listener function "
      +        "or access it via context.set_status instead.",
      +        DeprecationWarning,
      +        stacklevel=2,
      +    )
           return AsyncSetStatus(self.client, self.channel_id, self.thread_ts)
      diff --git a/docs/reference/context/assistant/thread_context_store/file/index.html b/docs/reference/context/assistant/thread_context_store/file/index.html index 4a5d944e1..cbb4e4db6 100644 --- a/docs/reference/context/assistant/thread_context_store/file/index.html +++ b/docs/reference/context/assistant/thread_context_store/file/index.html @@ -48,7 +48,7 @@

      Classes

      class FileAssistantThreadContextStore -(base_dir: str = '/Users/wbergamin/.bolt-app-assistant-thread-contexts') +(base_dir: str = '/Users/eden.zimbelman/.bolt-app-assistant-thread-contexts')
      diff --git a/docs/reference/context/async_context.html b/docs/reference/context/async_context.html index 9ce4ebd9e..8fc6d36bf 100644 --- a/docs/reference/context/async_context.html +++ b/docs/reference/context/async_context.html @@ -80,7 +80,7 @@

      Classes

      # The return type is intentionally string to avoid circular imports @property - def listener_runner(self) -> "AsyncioListenerRunner": # type: ignore[name-defined] + def listener_runner(self) -> "AsyncioListenerRunner": """The properly configured listener_runner that is available for middleware/listeners.""" return self["listener_runner"] @@ -149,7 +149,7 @@

      Classes

      Callable `say()` function """ if "say" not in self: - self["say"] = AsyncSay(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = AsyncSay(client=self.client, channel=self.channel_id) return self["say"] @property @@ -242,6 +242,10 @@

      Classes

      def get_thread_context(self) -> Optional[AsyncGetThreadContext]: return self.get("get_thread_context") + @property + def say_stream(self) -> Optional[AsyncSayStream]: + return self.get("say_stream") + @property def save_thread_context(self) -> Optional[AsyncSaveThreadContext]: return self.get("save_thread_context")
      @@ -457,7 +461,7 @@

      Returns

      Expand source code
      @property
      -def listener_runner(self) -> "AsyncioListenerRunner":  # type: ignore[name-defined]
      +def listener_runner(self) -> "AsyncioListenerRunner":
           """The properly configured listener_runner that is available for middleware/listeners."""
           return self["listener_runner"]
      @@ -547,7 +551,7 @@

      Returns

      Callable `say()` function """ if "say" not in self: - self["say"] = AsyncSay(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = AsyncSay(client=self.client, channel=self.channel_id) return self["say"]

      say() function for this request.

      @@ -565,6 +569,18 @@

      Returns

      Returns

      Callable say() function

      +
      prop say_streamAsyncSayStream | None
      +
      +
      + +Expand source code + +
      @property
      +def say_stream(self) -> Optional[AsyncSayStream]:
      +    return self.get("say_stream")
      +
      +
      +
      prop set_statusAsyncSetStatus | None
      @@ -694,6 +710,7 @@

      respond
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/context/base_context.html b/docs/reference/context/base_context.html index 4a177f8dc..afe571163 100644 --- a/docs/reference/context/base_context.html +++ b/docs/reference/context/base_context.html @@ -89,6 +89,7 @@

      Classes

      "set_status", "set_title", "set_suggested_prompts", + "say_stream", ] # Note that these items are not copyable, so when you add new items to this list, # you must modify ThreadListenerRunner/AsyncioListenerRunner's _build_lazy_request method to pass the values. diff --git a/docs/reference/context/context.html b/docs/reference/context/context.html index 615432502..a7b531c20 100644 --- a/docs/reference/context/context.html +++ b/docs/reference/context/context.html @@ -81,7 +81,7 @@

      Classes

      # The return type is intentionally string to avoid circular imports @property - def listener_runner(self) -> "ThreadListenerRunner": # type: ignore[name-defined] + def listener_runner(self) -> "ThreadListenerRunner": """The properly configured listener_runner that is available for middleware/listeners.""" return self["listener_runner"] @@ -150,7 +150,7 @@

      Classes

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"] @property @@ -243,6 +243,10 @@

      Classes

      def get_thread_context(self) -> Optional[GetThreadContext]: return self.get("get_thread_context") + @property + def say_stream(self) -> Optional[SayStream]: + return self.get("say_stream") + @property def save_thread_context(self) -> Optional[SaveThreadContext]: return self.get("save_thread_context") @@ -458,7 +462,7 @@

      Returns

      Expand source code
      @property
      -def listener_runner(self) -> "ThreadListenerRunner":  # type: ignore[name-defined]
      +def listener_runner(self) -> "ThreadListenerRunner":
           """The properly configured listener_runner that is available for middleware/listeners."""
           return self["listener_runner"]
      @@ -548,7 +552,7 @@

      Returns

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"]

      say() function for this request.

      @@ -566,6 +570,18 @@

      Returns

      Returns

      Callable say() function

      +
      prop say_streamSayStream | None
      +
      +
      + +Expand source code + +
      @property
      +def say_stream(self) -> Optional[SayStream]:
      +    return self.get("say_stream")
      +
      +
      +
      prop set_statusSetStatus | None
      @@ -696,6 +712,7 @@

      respond
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/context/get_thread_context/async_get_thread_context.html b/docs/reference/context/get_thread_context/async_get_thread_context.html index 1c3fc4d6c..967581b50 100644 --- a/docs/reference/context/get_thread_context/async_get_thread_context.html +++ b/docs/reference/context/get_thread_context/async_get_thread_context.html @@ -82,14 +82,10 @@

      Classes

      if self.thread_context_loaded is True: return self._thread_context - if self.payload.get("assistant_thread") is not None: + thread = self.payload.get("assistant_thread") + if isinstance(thread, dict) and thread.get("context", {}).get("channel_id") is not None: # assistant_thread_started - thread = self.payload["assistant_thread"] - self._thread_context = ( - AssistantThreadContext(thread["context"]) - if thread.get("context", {}).get("channel_id") is not None - else None - ) + self._thread_context = AssistantThreadContext(thread["context"]) # for this event, the context will never be changed self.thread_context_loaded = True elif self.payload.get("channel") is not None and self.payload.get("thread_ts") is not None: diff --git a/docs/reference/context/get_thread_context/get_thread_context.html b/docs/reference/context/get_thread_context/get_thread_context.html index 4ac274368..cf2e17a86 100644 --- a/docs/reference/context/get_thread_context/get_thread_context.html +++ b/docs/reference/context/get_thread_context/get_thread_context.html @@ -82,14 +82,10 @@

      Classes

      if self.thread_context_loaded is True: return self._thread_context - if self.payload.get("assistant_thread") is not None: + thread = self.payload.get("assistant_thread") + if isinstance(thread, dict) and thread.get("context", {}).get("channel_id") is not None: # assistant_thread_started - thread = self.payload["assistant_thread"] - self._thread_context = ( - AssistantThreadContext(thread["context"]) - if thread.get("context", {}).get("channel_id") is not None - else None - ) + self._thread_context = AssistantThreadContext(thread["context"]) # for this event, the context will never be changed self.thread_context_loaded = True elif self.payload.get("channel") is not None and self.payload.get("thread_ts") is not None: diff --git a/docs/reference/context/get_thread_context/index.html b/docs/reference/context/get_thread_context/index.html index 13dcd1388..5f9e38e71 100644 --- a/docs/reference/context/get_thread_context/index.html +++ b/docs/reference/context/get_thread_context/index.html @@ -93,14 +93,10 @@

      Classes

      if self.thread_context_loaded is True: return self._thread_context - if self.payload.get("assistant_thread") is not None: + thread = self.payload.get("assistant_thread") + if isinstance(thread, dict) and thread.get("context", {}).get("channel_id") is not None: # assistant_thread_started - thread = self.payload["assistant_thread"] - self._thread_context = ( - AssistantThreadContext(thread["context"]) - if thread.get("context", {}).get("channel_id") is not None - else None - ) + self._thread_context = AssistantThreadContext(thread["context"]) # for this event, the context will never be changed self.thread_context_loaded = True elif self.payload.get("channel") is not None and self.payload.get("thread_ts") is not None: diff --git a/docs/reference/context/index.html b/docs/reference/context/index.html index c761aa47e..ebdfe8aa8 100644 --- a/docs/reference/context/index.html +++ b/docs/reference/context/index.html @@ -89,6 +89,10 @@

      Sub-modules

      +
      slack_bolt.context.say_stream
      +
      +
      +
      slack_bolt.context.set_status
      @@ -145,7 +149,7 @@

      Classes

      # The return type is intentionally string to avoid circular imports @property - def listener_runner(self) -> "ThreadListenerRunner": # type: ignore[name-defined] + def listener_runner(self) -> "ThreadListenerRunner": """The properly configured listener_runner that is available for middleware/listeners.""" return self["listener_runner"] @@ -214,7 +218,7 @@

      Classes

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"] @property @@ -307,6 +311,10 @@

      Classes

      def get_thread_context(self) -> Optional[GetThreadContext]: return self.get("get_thread_context") + @property + def say_stream(self) -> Optional[SayStream]: + return self.get("say_stream") + @property def save_thread_context(self) -> Optional[SaveThreadContext]: return self.get("save_thread_context") @@ -522,7 +530,7 @@

      Returns

      Expand source code
      @property
      -def listener_runner(self) -> "ThreadListenerRunner":  # type: ignore[name-defined]
      +def listener_runner(self) -> "ThreadListenerRunner":
           """The properly configured listener_runner that is available for middleware/listeners."""
           return self["listener_runner"]
      @@ -612,7 +620,7 @@

      Returns

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"]

      slack_bolt.context.say function for this request.

      @@ -630,6 +638,18 @@

      Returns

      Returns

      Callable slack_bolt.context.say function

      +
      prop say_streamSayStream | None
      +
      +
      + +Expand source code + +
      @property
      +def say_stream(self) -> Optional[SayStream]:
      +    return self.get("say_stream")
      +
      +
      +
      prop set_statusSetStatus | None
      @@ -759,6 +779,7 @@

      Inherited members

    • slack_bolt.context.respond
    • slack_bolt.context.save_thread_context
    • slack_bolt.context.say
    • +
    • slack_bolt.context.say_stream
    • slack_bolt.context.set_status
    • slack_bolt.context.set_suggested_prompts
    • slack_bolt.context.set_title
    • @@ -778,6 +799,7 @@

      respond
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/context/say_stream/async_say_stream.html b/docs/reference/context/say_stream/async_say_stream.html new file mode 100644 index 000000000..4010b284d --- /dev/null +++ b/docs/reference/context/say_stream/async_say_stream.html @@ -0,0 +1,174 @@ + + + + + + +slack_bolt.context.say_stream.async_say_stream API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.context.say_stream.async_say_stream

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class AsyncSayStream +(*,
      client: slack_sdk.web.async_client.AsyncWebClient,
      channel: str | None = None,
      recipient_team_id: str | None = None,
      recipient_user_id: str | None = None,
      thread_ts: str | None = None)
      +
      +
      +
      + +Expand source code + +
      class AsyncSayStream:
      +    client: AsyncWebClient
      +    channel: Optional[str]
      +    recipient_team_id: Optional[str]
      +    recipient_user_id: Optional[str]
      +    thread_ts: Optional[str]
      +
      +    def __init__(
      +        self,
      +        *,
      +        client: AsyncWebClient,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +    ):
      +        self.client = client
      +        self.channel = channel
      +        self.recipient_team_id = recipient_team_id
      +        self.recipient_user_id = recipient_user_id
      +        self.thread_ts = thread_ts
      +
      +    async def __call__(
      +        self,
      +        *,
      +        buffer_size: Optional[int] = None,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +        **kwargs,
      +    ) -> AsyncChatStream:
      +        """Starts a new chat stream with context."""
      +        channel = channel or self.channel
      +        thread_ts = thread_ts or self.thread_ts
      +        if channel is None:
      +            raise ValueError("say_stream without channel here is unsupported")
      +        if thread_ts is None:
      +            raise ValueError("say_stream without thread_ts here is unsupported")
      +
      +        if buffer_size is not None:
      +            return await self.client.chat_stream(
      +                buffer_size=buffer_size,
      +                channel=channel,
      +                recipient_team_id=recipient_team_id or self.recipient_team_id,
      +                recipient_user_id=recipient_user_id or self.recipient_user_id,
      +                thread_ts=thread_ts,
      +                **kwargs,
      +            )
      +        return await self.client.chat_stream(
      +            channel=channel,
      +            recipient_team_id=recipient_team_id or self.recipient_team_id,
      +            recipient_user_id=recipient_user_id or self.recipient_user_id,
      +            thread_ts=thread_ts,
      +            **kwargs,
      +        )
      +
      +
      +

      Class variables

      +
      +
      var channel : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var client : slack_sdk.web.async_client.AsyncWebClient
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_team_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_user_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var thread_ts : str | None
      +
      +

      The type of the None singleton.

      +
      +
      +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/context/say_stream/index.html b/docs/reference/context/say_stream/index.html new file mode 100644 index 000000000..645942c72 --- /dev/null +++ b/docs/reference/context/say_stream/index.html @@ -0,0 +1,191 @@ + + + + + + +slack_bolt.context.say_stream API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.context.say_stream

      +
      +
      +
      +
      +

      Sub-modules

      +
      +
      slack_bolt.context.say_stream.async_say_stream
      +
      +
      +
      +
      slack_bolt.context.say_stream.say_stream
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class SayStream +(*,
      client: slack_sdk.web.client.WebClient,
      channel: str | None = None,
      recipient_team_id: str | None = None,
      recipient_user_id: str | None = None,
      thread_ts: str | None = None)
      +
      +
      +
      + +Expand source code + +
      class SayStream:
      +    client: WebClient
      +    channel: Optional[str]
      +    recipient_team_id: Optional[str]
      +    recipient_user_id: Optional[str]
      +    thread_ts: Optional[str]
      +
      +    def __init__(
      +        self,
      +        *,
      +        client: WebClient,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +    ):
      +        self.client = client
      +        self.channel = channel
      +        self.recipient_team_id = recipient_team_id
      +        self.recipient_user_id = recipient_user_id
      +        self.thread_ts = thread_ts
      +
      +    def __call__(
      +        self,
      +        *,
      +        buffer_size: Optional[int] = None,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +        **kwargs,
      +    ) -> ChatStream:
      +        """Starts a new chat stream with context."""
      +        channel = channel or self.channel
      +        thread_ts = thread_ts or self.thread_ts
      +        if channel is None:
      +            raise ValueError("say_stream without channel here is unsupported")
      +        if thread_ts is None:
      +            raise ValueError("say_stream without thread_ts here is unsupported")
      +
      +        if buffer_size is not None:
      +            return self.client.chat_stream(
      +                buffer_size=buffer_size,
      +                channel=channel,
      +                recipient_team_id=recipient_team_id or self.recipient_team_id,
      +                recipient_user_id=recipient_user_id or self.recipient_user_id,
      +                thread_ts=thread_ts,
      +                **kwargs,
      +            )
      +        return self.client.chat_stream(
      +            channel=channel,
      +            recipient_team_id=recipient_team_id or self.recipient_team_id,
      +            recipient_user_id=recipient_user_id or self.recipient_user_id,
      +            thread_ts=thread_ts,
      +            **kwargs,
      +        )
      +
      +
      +

      Class variables

      +
      +
      var channel : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var client : slack_sdk.web.client.WebClient
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_team_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_user_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var thread_ts : str | None
      +
      +

      The type of the None singleton.

      +
      +
      +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/context/say_stream/say_stream.html b/docs/reference/context/say_stream/say_stream.html new file mode 100644 index 000000000..784a58bbe --- /dev/null +++ b/docs/reference/context/say_stream/say_stream.html @@ -0,0 +1,174 @@ + + + + + + +slack_bolt.context.say_stream.say_stream API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.context.say_stream.say_stream

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class SayStream +(*,
      client: slack_sdk.web.client.WebClient,
      channel: str | None = None,
      recipient_team_id: str | None = None,
      recipient_user_id: str | None = None,
      thread_ts: str | None = None)
      +
      +
      +
      + +Expand source code + +
      class SayStream:
      +    client: WebClient
      +    channel: Optional[str]
      +    recipient_team_id: Optional[str]
      +    recipient_user_id: Optional[str]
      +    thread_ts: Optional[str]
      +
      +    def __init__(
      +        self,
      +        *,
      +        client: WebClient,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +    ):
      +        self.client = client
      +        self.channel = channel
      +        self.recipient_team_id = recipient_team_id
      +        self.recipient_user_id = recipient_user_id
      +        self.thread_ts = thread_ts
      +
      +    def __call__(
      +        self,
      +        *,
      +        buffer_size: Optional[int] = None,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +        **kwargs,
      +    ) -> ChatStream:
      +        """Starts a new chat stream with context."""
      +        channel = channel or self.channel
      +        thread_ts = thread_ts or self.thread_ts
      +        if channel is None:
      +            raise ValueError("say_stream without channel here is unsupported")
      +        if thread_ts is None:
      +            raise ValueError("say_stream without thread_ts here is unsupported")
      +
      +        if buffer_size is not None:
      +            return self.client.chat_stream(
      +                buffer_size=buffer_size,
      +                channel=channel,
      +                recipient_team_id=recipient_team_id or self.recipient_team_id,
      +                recipient_user_id=recipient_user_id or self.recipient_user_id,
      +                thread_ts=thread_ts,
      +                **kwargs,
      +            )
      +        return self.client.chat_stream(
      +            channel=channel,
      +            recipient_team_id=recipient_team_id or self.recipient_team_id,
      +            recipient_user_id=recipient_user_id or self.recipient_user_id,
      +            thread_ts=thread_ts,
      +            **kwargs,
      +        )
      +
      +
      +

      Class variables

      +
      +
      var channel : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var client : slack_sdk.web.client.WebClient
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_team_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_user_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var thread_ts : str | None
      +
      +

      The type of the None singleton.

      +
      +
      +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/error/index.html b/docs/reference/error/index.html index 9a9998e63..f57d690e9 100644 --- a/docs/reference/error/index.html +++ b/docs/reference/error/index.html @@ -72,7 +72,7 @@

      Subclasses

      class BoltUnhandledRequestError -(*,
      request: BoltRequest | AsyncBoltRequest,
      current_response: BoltResponse | None,
      last_global_middleware_name: str | None = None)
      +(*,
      request: ForwardRef('BoltRequest') | ForwardRef('AsyncBoltRequest'),
      current_response: ForwardRef('BoltResponse') | None,
      last_global_middleware_name: str | None = None)
      diff --git a/docs/reference/index.html b/docs/reference/index.html index 1c02a8aeb..b2d19719d 100644 --- a/docs/reference/index.html +++ b/docs/reference/index.html @@ -188,7 +188,7 @@

      Class variables

      class App -(*,
      logger: logging.Logger | None = None,
      name: str | None = None,
      process_before_response: bool = False,
      raise_error_for_unhandled_request: bool = False,
      signing_secret: str | None = None,
      token: str | None = None,
      token_verification_enabled: bool = True,
      client: slack_sdk.web.client.WebClient | None = None,
      before_authorize: Middleware | Callable[..., Any] | None = None,
      authorize: Callable[..., AuthorizeResult] | None = None,
      user_facing_authorize_error_message: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
      installation_store_bot_only: bool | None = None,
      request_verification_enabled: bool = True,
      ignoring_self_events_enabled: bool = True,
      ignoring_self_assistant_message_events_enabled: bool = True,
      ssl_check_enabled: bool = True,
      url_verification_enabled: bool = True,
      attaching_function_token_enabled: bool = True,
      oauth_settings: OAuthSettings | None = None,
      oauth_flow: OAuthFlow | None = None,
      verification_token: str | None = None,
      listener_executor: concurrent.futures._base.Executor | None = None,
      assistant_thread_context_store: AssistantThreadContextStore | None = None)
      +(*,
      logger: logging.Logger | None = None,
      name: str | None = None,
      process_before_response: bool = False,
      raise_error_for_unhandled_request: bool = False,
      signing_secret: str | None = None,
      token: str | None = None,
      token_verification_enabled: bool = True,
      client: slack_sdk.web.client.WebClient | None = None,
      before_authorize: Middleware | Callable[..., Any] | None = None,
      authorize: Callable[..., AuthorizeResult] | None = None,
      user_facing_authorize_error_message: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
      installation_store_bot_only: bool | None = None,
      request_verification_enabled: bool = True,
      ignoring_self_events_enabled: bool = True,
      ignoring_self_assistant_message_events_enabled: bool = True,
      ssl_check_enabled: bool = True,
      url_verification_enabled: bool = True,
      attaching_function_token_enabled: bool = True,
      oauth_settings: OAuthSettings | None = None,
      oauth_flow: OAuthFlow | None = None,
      verification_token: str | None = None,
      listener_executor: concurrent.futures._base.Executor | None = None,
      assistant_thread_context_store: AssistantThreadContextStore | None = None,
      attaching_conversation_kwargs_enabled: bool = True)
      @@ -235,6 +235,7 @@

      Class variables

      listener_executor: Optional[Executor] = None, # for AI Agents & Assistants assistant_thread_context_store: Optional[AssistantThreadContextStore] = None, + attaching_conversation_kwargs_enabled: bool = True, ): """Bolt App that provides functionalities to register middleware/listeners. @@ -455,6 +456,7 @@

      Class variables

      listener_executor = ThreadPoolExecutor(max_workers=5) self._assistant_thread_context_store = assistant_thread_context_store + self._attaching_conversation_kwargs_enabled = attaching_conversation_kwargs_enabled self._process_before_response = process_before_response self._listener_runner = ThreadListenerRunner( @@ -939,10 +941,13 @@

      Class variables

      middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -1000,6 +1005,8 @@

      Class variables

      primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -1496,20 +1503,6 @@

      Class variables

      # It is intended for apps that start lazy listeners from their custom global middleware. req.context["listener_runner"] = self.listener_runner - # For AI Agents & Assistants - if is_assistant_event(req.body): - assistant = AssistantUtilities( - payload=to_event(req.body), # type:ignore[arg-type] - context=req.context, - thread_context_store=self._assistant_thread_context_store, - ) - req.context["say"] = assistant.say - req.context["set_status"] = assistant.set_status - req.context["set_title"] = assistant.set_title - req.context["set_suggested_prompts"] = assistant.set_suggested_prompts - req.context["get_thread_context"] = assistant.get_thread_context - req.context["save_thread_context"] = assistant.save_thread_context - @staticmethod def _to_listener_functions( kwargs: dict, @@ -1555,7 +1548,7 @@

      Class variables

      CustomListener( app_name=self.name, ack_function=functions.pop(0), - lazy_functions=functions, # type:ignore[arg-type] + lazy_functions=functions, # type: ignore[arg-type] matchers=listener_matchers, middleware=listener_middleware, auto_acknowledgement=auto_acknowledgement, @@ -2343,10 +2336,13 @@

      Args

      middleware: A list of lister middleware functions. Only when all the middleware call `next()` method, the listener function can be invoked. """ + middleware = list(middleware) if middleware else [] def __call__(*args, **kwargs): functions = self._to_listener_functions(kwargs) if kwargs else list(args) primary_matcher = builtin_matchers.event(event, base_logger=self._base_logger) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) return __call__ @@ -2550,6 +2546,8 @@

      Args

      primary_matcher = builtin_matchers.message_event( keyword=keyword, constraints=constraints, base_logger=self._base_logger ) + if self._attaching_conversation_kwargs_enabled: + middleware.insert(0, AttachingConversationKwargs(self._assistant_thread_context_store)) middleware.insert(0, MessageListenerMatches(keyword)) return self._register_listener(list(functions), primary_matcher, matchers, middleware, True) @@ -3179,7 +3177,7 @@

      Args

      class Args -(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      next: Callable[[], None],
      **kwargs)
      +(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      say_stream: SayStream | None = None,
      next: Callable[[], None],
      **kwargs)
      @@ -3270,6 +3268,8 @@

      Args

      """`get_thread_context()` utility function for AI Agents & Assistants""" save_thread_context: Optional[SaveThreadContext] """`save_thread_context()` utility function for AI Agents & Assistants""" + say_stream: Optional[SayStream] + """`say_stream()` utility function for conversations, AI Agents & Assistants""" # middleware next: Callable[[], None] """`next()` utility function, which tells the middleware chain that it can continue with the next one""" @@ -3303,6 +3303,7 @@

      Args

      set_suggested_prompts: Optional[SetSuggestedPrompts] = None, get_thread_context: Optional[GetThreadContext] = None, save_thread_context: Optional[SaveThreadContext] = None, + say_stream: Optional[SayStream] = None, # As this method is not supposed to be invoked by bolt-python users, # the naming conflict with the built-in one affects # only the internals of this method @@ -3336,6 +3337,7 @@

      Args

      self.set_suggested_prompts = set_suggested_prompts self.get_thread_context = get_thread_context self.save_thread_context = save_thread_context + self.say_stream = say_stream self.next: Callable[[], None] = next self.next_: Callable[[], None] = next @@ -3459,6 +3461,10 @@

      Class variables

      say() utility function, which calls chat.postMessage API with the associated channel ID

      +
      var say_streamSayStream | None
      +
      +

      say_stream() utility function for conversations, AI Agents & Assistants

      +
      var set_statusSetStatus | None

      set_status() utility function for AI Agents & Assistants

      @@ -3531,7 +3537,7 @@

      Class variables

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3570,7 +3576,7 @@

      Class variables

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3609,7 +3615,7 @@

      Class variables

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3648,7 +3654,7 @@

      Class variables

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3678,13 +3684,13 @@

      Class variables

      ): return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + ( custom_matchers or [] - ) # type:ignore[operator] + ) # 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] + def process( # type: ignore[return] self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse] ) -> Optional[BoltResponse]: if self._thread_context_changed_listeners is None: @@ -3700,6 +3706,15 @@

      Class variables

      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(). + # Skip this listener and try the next one. + continue + if middleware_resp is not None: + resp = middleware_resp return listener_runner.run( request=req, response=resp, @@ -3719,13 +3734,14 @@

      Class variables

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -3734,7 +3750,7 @@

      Class variables

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -3813,7 +3829,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3853,13 +3869,14 @@

      Methods

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -3868,7 +3885,7 @@

      Methods

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -3914,7 +3931,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -3963,7 +3980,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -4012,7 +4029,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -4185,7 +4202,7 @@

      Methods

      # The return type is intentionally string to avoid circular imports @property - def listener_runner(self) -> "ThreadListenerRunner": # type: ignore[name-defined] + def listener_runner(self) -> "ThreadListenerRunner": """The properly configured listener_runner that is available for middleware/listeners.""" return self["listener_runner"] @@ -4254,7 +4271,7 @@

      Methods

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"] @property @@ -4347,6 +4364,10 @@

      Methods

      def get_thread_context(self) -> Optional[GetThreadContext]: return self.get("get_thread_context") + @property + def say_stream(self) -> Optional[SayStream]: + return self.get("say_stream") + @property def save_thread_context(self) -> Optional[SaveThreadContext]: return self.get("save_thread_context") @@ -4562,7 +4583,7 @@

      Returns

      Expand source code
      @property
      -def listener_runner(self) -> "ThreadListenerRunner":  # type: ignore[name-defined]
      +def listener_runner(self) -> "ThreadListenerRunner":
           """The properly configured listener_runner that is available for middleware/listeners."""
           return self["listener_runner"]
      @@ -4652,7 +4673,7 @@

      Returns

      Callable `say()` function """ if "say" not in self: - self["say"] = Say(client=self.client, channel=self.channel_id, thread_ts=self.thread_ts) + self["say"] = Say(client=self.client, channel=self.channel_id) return self["say"]

      say() function for this request.

      @@ -4670,6 +4691,18 @@

      Returns

      Returns

      Callable say() function

      +
      prop say_streamSayStream | None
      +
      +
      + +Expand source code + +
      @property
      +def say_stream(self) -> Optional[SayStream]:
      +    return self.get("say_stream")
      +
      +
      +
      prop set_statusSetStatus | None
      @@ -5304,7 +5337,7 @@

      Returns

      class FileAssistantThreadContextStore -(base_dir: str = '/Users/wbergamin/.bolt-app-assistant-thread-contexts') +(base_dir: str = '/Users/eden.zimbelman/.bolt-app-assistant-thread-contexts')
      @@ -5843,6 +5876,97 @@

      Class variables

      +
      +class SayStream +(*,
      client: slack_sdk.web.client.WebClient,
      channel: str | None = None,
      recipient_team_id: str | None = None,
      recipient_user_id: str | None = None,
      thread_ts: str | None = None)
      +
      +
      +
      + +Expand source code + +
      class SayStream:
      +    client: WebClient
      +    channel: Optional[str]
      +    recipient_team_id: Optional[str]
      +    recipient_user_id: Optional[str]
      +    thread_ts: Optional[str]
      +
      +    def __init__(
      +        self,
      +        *,
      +        client: WebClient,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +    ):
      +        self.client = client
      +        self.channel = channel
      +        self.recipient_team_id = recipient_team_id
      +        self.recipient_user_id = recipient_user_id
      +        self.thread_ts = thread_ts
      +
      +    def __call__(
      +        self,
      +        *,
      +        buffer_size: Optional[int] = None,
      +        channel: Optional[str] = None,
      +        recipient_team_id: Optional[str] = None,
      +        recipient_user_id: Optional[str] = None,
      +        thread_ts: Optional[str] = None,
      +        **kwargs,
      +    ) -> ChatStream:
      +        """Starts a new chat stream with context."""
      +        channel = channel or self.channel
      +        thread_ts = thread_ts or self.thread_ts
      +        if channel is None:
      +            raise ValueError("say_stream without channel here is unsupported")
      +        if thread_ts is None:
      +            raise ValueError("say_stream without thread_ts here is unsupported")
      +
      +        if buffer_size is not None:
      +            return self.client.chat_stream(
      +                buffer_size=buffer_size,
      +                channel=channel,
      +                recipient_team_id=recipient_team_id or self.recipient_team_id,
      +                recipient_user_id=recipient_user_id or self.recipient_user_id,
      +                thread_ts=thread_ts,
      +                **kwargs,
      +            )
      +        return self.client.chat_stream(
      +            channel=channel,
      +            recipient_team_id=recipient_team_id or self.recipient_team_id,
      +            recipient_user_id=recipient_user_id or self.recipient_user_id,
      +            thread_ts=thread_ts,
      +            **kwargs,
      +        )
      +
      +
      +

      Class variables

      +
      +
      var channel : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var client : slack_sdk.web.client.WebClient
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_team_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var recipient_user_id : str | None
      +
      +

      The type of the None singleton.

      +
      +
      var thread_ts : str | None
      +
      +

      The type of the None singleton.

      +
      +
      +
      class SetStatus (client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str) @@ -6110,6 +6234,7 @@

      Args

      response
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • @@ -6157,6 +6282,7 @@

      BoltC
    • respond
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • @@ -6262,6 +6388,16 @@

      Say

  • +

    SayStream

    + +
  • +
  • SetStatus

    • channel_id
    • diff --git a/docs/reference/kwargs_injection/args.html b/docs/reference/kwargs_injection/args.html index 4d03687d1..bbba71eb8 100644 --- a/docs/reference/kwargs_injection/args.html +++ b/docs/reference/kwargs_injection/args.html @@ -48,7 +48,7 @@

      Classes

      class Args -(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      next: Callable[[], None],
      **kwargs)
      +(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      say_stream: SayStream | None = None,
      next: Callable[[], None],
      **kwargs)
      @@ -139,6 +139,8 @@

      Classes

      """`get_thread_context()` utility function for AI Agents & Assistants""" save_thread_context: Optional[SaveThreadContext] """`save_thread_context()` utility function for AI Agents & Assistants""" + say_stream: Optional[SayStream] + """`say_stream()` utility function for conversations, AI Agents & Assistants""" # middleware next: Callable[[], None] """`next()` utility function, which tells the middleware chain that it can continue with the next one""" @@ -172,6 +174,7 @@

      Classes

      set_suggested_prompts: Optional[SetSuggestedPrompts] = None, get_thread_context: Optional[GetThreadContext] = None, save_thread_context: Optional[SaveThreadContext] = None, + say_stream: Optional[SayStream] = None, # As this method is not supposed to be invoked by bolt-python users, # the naming conflict with the built-in one affects # only the internals of this method @@ -205,6 +208,7 @@

      Classes

      self.set_suggested_prompts = set_suggested_prompts self.get_thread_context = get_thread_context self.save_thread_context = save_thread_context + self.say_stream = say_stream self.next: Callable[[], None] = next self.next_: Callable[[], None] = next
      @@ -328,6 +332,10 @@

      Class variables

      say() utility function, which calls chat.postMessage API with the associated channel ID

      +
      var say_streamSayStream | None
      +
      +

      say_stream() utility function for conversations, AI Agents & Assistants

      +
      var set_statusSetStatus | None

      set_status() utility function for AI Agents & Assistants

      @@ -391,6 +399,7 @@

      response
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/kwargs_injection/async_args.html b/docs/reference/kwargs_injection/async_args.html index 959f35a43..5b0e7b70e 100644 --- a/docs/reference/kwargs_injection/async_args.html +++ b/docs/reference/kwargs_injection/async_args.html @@ -48,7 +48,7 @@

      Classes

      class AsyncArgs -(*,
      logger: logging.Logger,
      client: slack_sdk.web.async_client.AsyncWebClient,
      req: AsyncBoltRequest,
      resp: BoltResponse,
      context: AsyncBoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: AsyncAck,
      say: AsyncSay,
      respond: AsyncRespond,
      complete: AsyncComplete,
      fail: AsyncFail,
      set_status: AsyncSetStatus | None = None,
      set_title: AsyncSetTitle | None = None,
      set_suggested_prompts: AsyncSetSuggestedPrompts | None = None,
      get_thread_context: AsyncGetThreadContext | None = None,
      save_thread_context: AsyncSaveThreadContext | None = None,
      next: Callable[[], Awaitable[None]],
      **kwargs)
      +(*,
      logger: logging.Logger,
      client: slack_sdk.web.async_client.AsyncWebClient,
      req: AsyncBoltRequest,
      resp: BoltResponse,
      context: AsyncBoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: AsyncAck,
      say: AsyncSay,
      respond: AsyncRespond,
      complete: AsyncComplete,
      fail: AsyncFail,
      set_status: AsyncSetStatus | None = None,
      set_title: AsyncSetTitle | None = None,
      set_suggested_prompts: AsyncSetSuggestedPrompts | None = None,
      get_thread_context: AsyncGetThreadContext | None = None,
      save_thread_context: AsyncSaveThreadContext | None = None,
      say_stream: AsyncSayStream | None = None,
      next: Callable[[], Awaitable[None]],
      **kwargs)
      @@ -139,6 +139,8 @@

      Classes

      """`get_thread_context()` utility function for AI Agents & Assistants""" save_thread_context: Optional[AsyncSaveThreadContext] """`save_thread_context()` utility function for AI Agents & Assistants""" + say_stream: Optional[AsyncSayStream] + """`say_stream()` utility function for AI Agents & Assistants""" # middleware next: Callable[[], Awaitable[None]] """`next()` utility function, which tells the middleware chain that it can continue with the next one""" @@ -172,6 +174,7 @@

      Classes

      set_suggested_prompts: Optional[AsyncSetSuggestedPrompts] = None, get_thread_context: Optional[AsyncGetThreadContext] = None, save_thread_context: Optional[AsyncSaveThreadContext] = None, + say_stream: Optional[AsyncSayStream] = None, next: Callable[[], Awaitable[None]], **kwargs, # noqa ): @@ -202,6 +205,7 @@

      Classes

      self.set_suggested_prompts = set_suggested_prompts self.get_thread_context = get_thread_context self.save_thread_context = save_thread_context + self.say_stream = say_stream self.next: Callable[[], Awaitable[None]] = next self.next_: Callable[[], Awaitable[None]] = next @@ -325,6 +329,10 @@

      Class variables

      say() utility function, which calls chat.postMessage API with the associated channel ID

      +
      var say_streamAsyncSayStream | None
      +
      +

      say_stream() utility function for AI Agents & Assistants

      +
      var set_statusAsyncSetStatus | None

      set_status() utility function for AI Agents & Assistants

      @@ -388,6 +396,7 @@

      response
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/kwargs_injection/async_utils.html b/docs/reference/kwargs_injection/async_utils.html index 80952518d..7af3a7679 100644 --- a/docs/reference/kwargs_injection/async_utils.html +++ b/docs/reference/kwargs_injection/async_utils.html @@ -63,7 +63,7 @@

      Functions

      error: Optional[Exception] = None, # for error handlers next_keys_required: bool = True, # False for listeners / middleware / error handlers ) -> Dict[str, Any]: - all_available_args = { + all_available_args: Dict[str, Any] = { "logger": logger, "client": request.context.client, "req": request, @@ -92,6 +92,7 @@

      Functions

      "set_suggested_prompts": request.context.set_suggested_prompts, "get_thread_context": request.context.get_thread_context, "save_thread_context": request.context.save_thread_context, + "say_stream": request.context.say_stream, # middleware "next": next_func, "next_": next_func, # for the middleware using Python's built-in `next()` function @@ -136,7 +137,7 @@

      Functions

      for name in required_arg_names: if name == "args": if isinstance(request, AsyncBoltRequest): - kwargs[name] = AsyncArgs(**all_available_args) # type: ignore[arg-type] + kwargs[name] = AsyncArgs(**all_available_args) else: logger.warning(f"Unknown Request object type detected ({type(request)})") diff --git a/docs/reference/kwargs_injection/index.html b/docs/reference/kwargs_injection/index.html index de7ef4a0a..cb17cea5d 100644 --- a/docs/reference/kwargs_injection/index.html +++ b/docs/reference/kwargs_injection/index.html @@ -85,7 +85,7 @@

      Functions

      error: Optional[Exception] = None, # for error handlers next_keys_required: bool = True, # False for listeners / middleware / error handlers ) -> Dict[str, Any]: - all_available_args = { + all_available_args: Dict[str, Any] = { "logger": logger, "client": request.context.client, "req": request, @@ -113,6 +113,7 @@

      Functions

      "set_title": request.context.set_title, "set_suggested_prompts": request.context.set_suggested_prompts, "save_thread_context": request.context.save_thread_context, + "say_stream": request.context.say_stream, # middleware "next": next_func, "next_": next_func, # for the middleware using Python's built-in `next()` function @@ -157,7 +158,7 @@

      Functions

      for name in required_arg_names: if name == "args": if isinstance(request, BoltRequest): - kwargs[name] = Args(**all_available_args) # type: ignore[arg-type] + kwargs[name] = Args(**all_available_args) else: logger.warning(f"Unknown Request object type detected ({type(request)})") @@ -175,7 +176,7 @@

      Classes

      class Args -(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      next: Callable[[], None],
      **kwargs)
      +(*,
      logger: logging.Logger,
      client: slack_sdk.web.client.WebClient,
      req: BoltRequest,
      resp: BoltResponse,
      context: BoltContext,
      body: Dict[str, Any],
      payload: Dict[str, Any],
      options: Dict[str, Any] | None = None,
      shortcut: Dict[str, Any] | None = None,
      action: Dict[str, Any] | None = None,
      view: Dict[str, Any] | None = None,
      command: Dict[str, Any] | None = None,
      event: Dict[str, Any] | None = None,
      message: Dict[str, Any] | None = None,
      ack: Ack,
      say: Say,
      respond: Respond,
      complete: Complete,
      fail: Fail,
      set_status: SetStatus | None = None,
      set_title: SetTitle | None = None,
      set_suggested_prompts: SetSuggestedPrompts | None = None,
      get_thread_context: GetThreadContext | None = None,
      save_thread_context: SaveThreadContext | None = None,
      say_stream: SayStream | None = None,
      next: Callable[[], None],
      **kwargs)
      @@ -266,6 +267,8 @@

      Classes

      """`get_thread_context()` utility function for AI Agents & Assistants""" save_thread_context: Optional[SaveThreadContext] """`save_thread_context()` utility function for AI Agents & Assistants""" + say_stream: Optional[SayStream] + """`say_stream()` utility function for conversations, AI Agents & Assistants""" # middleware next: Callable[[], None] """`next()` utility function, which tells the middleware chain that it can continue with the next one""" @@ -299,6 +302,7 @@

      Classes

      set_suggested_prompts: Optional[SetSuggestedPrompts] = None, get_thread_context: Optional[GetThreadContext] = None, save_thread_context: Optional[SaveThreadContext] = None, + say_stream: Optional[SayStream] = None, # As this method is not supposed to be invoked by bolt-python users, # the naming conflict with the built-in one affects # only the internals of this method @@ -332,6 +336,7 @@

      Classes

      self.set_suggested_prompts = set_suggested_prompts self.get_thread_context = get_thread_context self.save_thread_context = save_thread_context + self.say_stream = say_stream self.next: Callable[[], None] = next self.next_: Callable[[], None] = next
      @@ -455,6 +460,10 @@

      Class variables

      say() utility function, which calls chat.postMessage API with the associated channel ID

      +
      var say_streamSayStream | None
      +
      +

      say_stream() utility function for conversations, AI Agents & Assistants

      +
      var set_statusSetStatus | None

      set_status() utility function for AI Agents & Assistants

      @@ -531,6 +540,7 @@

      response
    • save_thread_context
    • say
    • +
    • say_stream
    • set_status
    • set_suggested_prompts
    • set_title
    • diff --git a/docs/reference/kwargs_injection/utils.html b/docs/reference/kwargs_injection/utils.html index 2e6ecd001..0289fd410 100644 --- a/docs/reference/kwargs_injection/utils.html +++ b/docs/reference/kwargs_injection/utils.html @@ -63,7 +63,7 @@

      Functions

      error: Optional[Exception] = None, # for error handlers next_keys_required: bool = True, # False for listeners / middleware / error handlers ) -> Dict[str, Any]: - all_available_args = { + all_available_args: Dict[str, Any] = { "logger": logger, "client": request.context.client, "req": request, @@ -91,6 +91,7 @@

      Functions

      "set_title": request.context.set_title, "set_suggested_prompts": request.context.set_suggested_prompts, "save_thread_context": request.context.save_thread_context, + "say_stream": request.context.say_stream, # middleware "next": next_func, "next_": next_func, # for the middleware using Python's built-in `next()` function @@ -135,7 +136,7 @@

      Functions

      for name in required_arg_names: if name == "args": if isinstance(request, BoltRequest): - kwargs[name] = Args(**all_available_args) # type: ignore[arg-type] + kwargs[name] = Args(**all_available_args) else: logger.warning(f"Unknown Request object type detected ({type(request)})") diff --git a/docs/reference/listener/async_listener_error_handler.html b/docs/reference/listener/async_listener_error_handler.html index 1f3789c40..ebee4441a 100644 --- a/docs/reference/listener/async_listener_error_handler.html +++ b/docs/reference/listener/async_listener_error_handler.html @@ -77,9 +77,10 @@

      Classes

      ) returned_response = await self.func(**kwargs) if returned_response is not None and isinstance(returned_response, BoltResponse): - response.status = returned_response.status # type: ignore[union-attr] - response.headers = returned_response.headers # type: ignore[union-attr] - response.body = returned_response.body # type: ignore[union-attr] + assert response is not None, "response must be provided when returning a BoltResponse from an error handler" + response.status = returned_response.status + response.headers = returned_response.headers + response.body = returned_response.body

      Ancestors

      diff --git a/docs/reference/listener/listener_error_handler.html b/docs/reference/listener/listener_error_handler.html index c9f7c2ccd..e344b15cb 100644 --- a/docs/reference/listener/listener_error_handler.html +++ b/docs/reference/listener/listener_error_handler.html @@ -77,9 +77,10 @@

      Classes

      ) returned_response = self.func(**kwargs) if returned_response is not None and isinstance(returned_response, BoltResponse): - response.status = returned_response.status # type: ignore[union-attr] - response.headers = returned_response.headers # type: ignore[union-attr] - response.body = returned_response.body # type: ignore[union-attr] + assert response is not None, "response must be provided when returning a BoltResponse from an error handler" + response.status = returned_response.status + response.headers = returned_response.headers + response.body = returned_response.body

      Ancestors

      diff --git a/docs/reference/logger/messages.html b/docs/reference/logger/messages.html index e69b45fc9..1072e6479 100644 --- a/docs/reference/logger/messages.html +++ b/docs/reference/logger/messages.html @@ -409,7 +409,7 @@

      Functions

      -def warning_unhandled_by_global_middleware(name: str,
      req: BoltRequest | AsyncBoltRequest) ‑> str
      +def warning_unhandled_by_global_middleware(name: str,
      req: BoltRequest | ForwardRef('AsyncBoltRequest')) ‑> str
      @@ -427,7 +427,7 @@

      Functions

      -def warning_unhandled_request(req: BoltRequest | AsyncBoltRequest) ‑> str +def warning_unhandled_request(req: BoltRequest | ForwardRef('AsyncBoltRequest')) ‑> str
      diff --git a/docs/reference/middleware/assistant/assistant.html b/docs/reference/middleware/assistant/assistant.html index d1184c407..946416d62 100644 --- a/docs/reference/middleware/assistant/assistant.html +++ b/docs/reference/middleware/assistant/assistant.html @@ -96,7 +96,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -135,7 +135,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -174,7 +174,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -213,7 +213,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -243,13 +243,13 @@

      Classes

      ): return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + ( custom_matchers or [] - ) # type:ignore[operator] + ) # 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] + def process( # type: ignore[return] self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse] ) -> Optional[BoltResponse]: if self._thread_context_changed_listeners is None: @@ -265,6 +265,15 @@

      Classes

      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(). + # Skip this listener and try the next one. + continue + if middleware_resp is not None: + resp = middleware_resp return listener_runner.run( request=req, response=resp, @@ -284,13 +293,14 @@

      Classes

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -299,7 +309,7 @@

      Classes

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -378,7 +388,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -418,13 +428,14 @@

      Methods

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -433,7 +444,7 @@

      Methods

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -479,7 +490,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -528,7 +539,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -577,7 +588,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func diff --git a/docs/reference/middleware/assistant/async_assistant.html b/docs/reference/middleware/assistant/async_assistant.html index 2faf0e34b..748be2cbf 100644 --- a/docs/reference/middleware/assistant/async_assistant.html +++ b/docs/reference/middleware/assistant/async_assistant.html @@ -94,7 +94,7 @@

      Classes

      func=is_assistant_thread_started_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -103,7 +103,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -140,7 +140,7 @@

      Classes

      func=is_user_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -149,7 +149,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -186,7 +186,7 @@

      Classes

      func=is_bot_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -195,7 +195,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -232,7 +232,7 @@

      Classes

      func=is_assistant_thread_context_changed_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -241,7 +241,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -269,14 +269,14 @@

      Classes

      primary_matcher: Union[Callable[..., bool], AsyncListenerMatcher], custom_matchers: Optional[Union[Callable[..., bool], AsyncListenerMatcher]], ): - return [primary_matcher] + (custom_matchers or []) # type:ignore[operator] + return [primary_matcher] + (custom_matchers or []) # type: ignore[operator] @staticmethod async def default_thread_context_changed(save_thread_context: AsyncSaveThreadContext, payload: dict): new_context: dict = payload["assistant_thread"]["context"] await save_thread_context(new_context) - async def async_process( # type:ignore[return] + async def async_process( # type: ignore[return] self, *, req: AsyncBoltRequest, @@ -296,6 +296,15 @@

      Classes

      if listeners is not None: for listener in listeners: if listener is not None and await listener.async_matches(req=req, resp=resp): + middleware_resp, next_was_not_called = await listener.run_async_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(). + # Skip this listener and try the next one. + continue + if middleware_resp is not None: + resp = middleware_resp return await listener_runner.run( request=req, response=resp, @@ -315,13 +324,14 @@

      Classes

      middleware: Optional[List[AsyncMiddleware]] = None, base_logger: Optional[Logger] = None, ) -> AsyncListener: - 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, Callable): # type: ignore[arg-type] + listener_or_functions = [listener_or_functions] # type: ignore[list-item] if isinstance(listener_or_functions, AsyncListener): return listener_or_functions elif isinstance(listener_or_functions, list): middleware = middleware if middleware else [] + middleware.insert(0, AsyncAttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -333,7 +343,7 @@

      Classes

      else: listener_matchers.append( build_listener_matcher( - func=matcher, # type:ignore[arg-type] + func=matcher, # type: ignore[arg-type] asyncio=True, base_logger=base_logger, ) @@ -408,7 +418,7 @@

      Methods

      func=is_bot_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -417,7 +427,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -457,13 +467,14 @@

      Methods

      middleware: Optional[List[AsyncMiddleware]] = None, base_logger: Optional[Logger] = None, ) -> AsyncListener: - 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, Callable): # type: ignore[arg-type] + listener_or_functions = [listener_or_functions] # type: ignore[list-item] if isinstance(listener_or_functions, AsyncListener): return listener_or_functions elif isinstance(listener_or_functions, list): middleware = middleware if middleware else [] + middleware.insert(0, AsyncAttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -475,7 +486,7 @@

      Methods

      else: listener_matchers.append( build_listener_matcher( - func=matcher, # type:ignore[arg-type] + func=matcher, # type: ignore[arg-type] asyncio=True, base_logger=base_logger, ) @@ -516,7 +527,7 @@

      Methods

      func=is_assistant_thread_context_changed_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -525,7 +536,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -572,7 +583,7 @@

      Methods

      func=is_assistant_thread_started_event, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -581,7 +592,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -628,7 +639,7 @@

      Methods

      func=is_user_message_event_in_assistant_thread, asyncio=True, base_logger=self.base_logger, - ), # type:ignore[arg-type] + ), # type: ignore[arg-type] matchers, ) if is_used_without_argument(args): @@ -637,7 +648,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func diff --git a/docs/reference/middleware/assistant/index.html b/docs/reference/middleware/assistant/index.html index 92f405cad..e9fce8d64 100644 --- a/docs/reference/middleware/assistant/index.html +++ b/docs/reference/middleware/assistant/index.html @@ -107,7 +107,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -146,7 +146,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -185,7 +185,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -224,7 +224,7 @@

      Classes

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -254,13 +254,13 @@

      Classes

      ): return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + ( custom_matchers or [] - ) # type:ignore[operator] + ) # 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] + def process( # type: ignore[return] self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse] ) -> Optional[BoltResponse]: if self._thread_context_changed_listeners is None: @@ -276,6 +276,15 @@

      Classes

      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(). + # Skip this listener and try the next one. + continue + if middleware_resp is not None: + resp = middleware_resp return listener_runner.run( request=req, response=resp, @@ -295,13 +304,14 @@

      Classes

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -310,7 +320,7 @@

      Classes

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -389,7 +399,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -429,13 +439,14 @@

      Methods

      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, 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, AttachingConversationKwargs(self.thread_context_store)) functions = listener_or_functions ack_function = functions.pop(0) @@ -444,7 +455,7 @@

      Methods

      for matcher in matchers: if isinstance(matcher, ListenerMatcher): listener_matchers.append(matcher) - elif isinstance(matcher, Callable): # type:ignore[arg-type] + elif isinstance(matcher, Callable): # type: ignore[arg-type] listener_matchers.append( build_listener_matcher( func=matcher, @@ -490,7 +501,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -539,7 +550,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func @@ -588,7 +599,7 @@

      Methods

      self.build_listener( listener_or_functions=func, matchers=all_matchers, - middleware=middleware, # type:ignore[arg-type] + middleware=middleware, # type: ignore[arg-type] ) ) return func diff --git a/docs/reference/middleware/async_builtins.html b/docs/reference/middleware/async_builtins.html index d32deff15..1ddea9222 100644 --- a/docs/reference/middleware/async_builtins.html +++ b/docs/reference/middleware/async_builtins.html @@ -46,6 +46,82 @@

      Module slack_bolt.middleware.async_builtins

      Classes

      +
      +class AsyncAttachingConversationKwargs +(thread_context_store: AsyncAssistantThreadContextStore | None = None) +
      +
      +
      + +Expand source code + +
      class AsyncAttachingConversationKwargs(AsyncMiddleware):
      +
      +    thread_context_store: Optional[AsyncAssistantThreadContextStore]
      +
      +    def __init__(self, thread_context_store: Optional[AsyncAssistantThreadContextStore] = None):
      +        self.thread_context_store = thread_context_store
      +
      +    async def async_process(
      +        self,
      +        *,
      +        req: AsyncBoltRequest,
      +        resp: BoltResponse,
      +        next: Callable[[], Awaitable[BoltResponse]],
      +    ) -> Optional[BoltResponse]:
      +        event = to_event(req.body)
      +        if event is not None:
      +            if is_assistant_event(req.body):
      +                assistant = AsyncAssistantUtilities(
      +                    payload=event,
      +                    context=req.context,
      +                    thread_context_store=self.thread_context_store,
      +                )
      +                req.context["say"] = assistant.say
      +                req.context["set_title"] = assistant.set_title
      +                req.context["set_suggested_prompts"] = assistant.set_suggested_prompts
      +                req.context["get_thread_context"] = assistant.get_thread_context
      +                req.context["save_thread_context"] = assistant.save_thread_context
      +
      +            # TODO: in the future we might want to introduce a "proper" extract_ts utility
      +            thread_ts = req.context.thread_ts or event.get("ts")
      +            if req.context.channel_id and thread_ts:
      +                req.context["set_status"] = AsyncSetStatus(
      +                    client=req.context.client,
      +                    channel_id=req.context.channel_id,
      +                    thread_ts=thread_ts,
      +                )
      +                req.context["say_stream"] = AsyncSayStream(
      +                    client=req.context.client,
      +                    channel=req.context.channel_id,
      +                    recipient_team_id=req.context.team_id or req.context.enterprise_id,
      +                    recipient_user_id=req.context.user_id,
      +                    thread_ts=thread_ts,
      +                )
      +        return await next()
      +
      +

      A middleware can process request data before other middleware and listener functions.

      +

      Ancestors

      + +

      Class variables

      +
      +
      var thread_context_storeAsyncAssistantThreadContextStore | None
      +
      +

      The type of the None singleton.

      +
      +
      +

      Inherited members

      + +
      class AsyncAttachingFunctionToken
      @@ -395,6 +471,12 @@

      Inherited members

    • Classes

      • +

        AsyncAttachingConversationKwargs

        + +
      • +
      • AsyncAttachingFunctionToken

      • diff --git a/docs/reference/middleware/async_middleware.html b/docs/reference/middleware/async_middleware.html index 33b4273e7..f7713b881 100644 --- a/docs/reference/middleware/async_middleware.html +++ b/docs/reference/middleware/async_middleware.html @@ -104,6 +104,7 @@

        Subclasses

        • AsyncAssistant
        • AsyncCustomMiddleware
        • +
        • AsyncAttachingConversationKwargs
        • AsyncAttachingFunctionToken
        • AsyncAuthorization
        • AsyncIgnoringSelfEvents
        • diff --git a/docs/reference/middleware/async_middleware_error_handler.html b/docs/reference/middleware/async_middleware_error_handler.html index e7cd8bb32..bf5b101f6 100644 --- a/docs/reference/middleware/async_middleware_error_handler.html +++ b/docs/reference/middleware/async_middleware_error_handler.html @@ -77,9 +77,10 @@

          Classes

          ) returned_response = await self.func(**kwargs) if returned_response is not None and isinstance(returned_response, BoltResponse): - response.status = returned_response.status # type: ignore[union-attr] - response.headers = returned_response.headers # type: ignore[union-attr] - response.body = returned_response.body # type: ignore[union-attr] + assert response is not None, "response must be provided when returning a BoltResponse from an error handler" + response.status = returned_response.status + response.headers = returned_response.headers + response.body = returned_response.body
    • Ancestors

      diff --git a/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html b/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html new file mode 100644 index 000000000..a0f5bdf85 --- /dev/null +++ b/docs/reference/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.html @@ -0,0 +1,155 @@ + + + + + + +slack_bolt.middleware.attaching_conversation_kwargs.async_attaching_conversation_kwargs API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.middleware.attaching_conversation_kwargs.async_attaching_conversation_kwargs

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class AsyncAttachingConversationKwargs +(thread_context_store: AsyncAssistantThreadContextStore | None = None) +
      +
      +
      + +Expand source code + +
      class AsyncAttachingConversationKwargs(AsyncMiddleware):
      +
      +    thread_context_store: Optional[AsyncAssistantThreadContextStore]
      +
      +    def __init__(self, thread_context_store: Optional[AsyncAssistantThreadContextStore] = None):
      +        self.thread_context_store = thread_context_store
      +
      +    async def async_process(
      +        self,
      +        *,
      +        req: AsyncBoltRequest,
      +        resp: BoltResponse,
      +        next: Callable[[], Awaitable[BoltResponse]],
      +    ) -> Optional[BoltResponse]:
      +        event = to_event(req.body)
      +        if event is not None:
      +            if is_assistant_event(req.body):
      +                assistant = AsyncAssistantUtilities(
      +                    payload=event,
      +                    context=req.context,
      +                    thread_context_store=self.thread_context_store,
      +                )
      +                req.context["say"] = assistant.say
      +                req.context["set_title"] = assistant.set_title
      +                req.context["set_suggested_prompts"] = assistant.set_suggested_prompts
      +                req.context["get_thread_context"] = assistant.get_thread_context
      +                req.context["save_thread_context"] = assistant.save_thread_context
      +
      +            # TODO: in the future we might want to introduce a "proper" extract_ts utility
      +            thread_ts = req.context.thread_ts or event.get("ts")
      +            if req.context.channel_id and thread_ts:
      +                req.context["set_status"] = AsyncSetStatus(
      +                    client=req.context.client,
      +                    channel_id=req.context.channel_id,
      +                    thread_ts=thread_ts,
      +                )
      +                req.context["say_stream"] = AsyncSayStream(
      +                    client=req.context.client,
      +                    channel=req.context.channel_id,
      +                    recipient_team_id=req.context.team_id or req.context.enterprise_id,
      +                    recipient_user_id=req.context.user_id,
      +                    thread_ts=thread_ts,
      +                )
      +        return await next()
      +
      +

      A middleware can process request data before other middleware and listener functions.

      +

      Ancestors

      + +

      Class variables

      +
      +
      var thread_context_storeAsyncAssistantThreadContextStore | None
      +
      +

      The type of the None singleton.

      +
      +
      +

      Inherited members

      + +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html b/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html new file mode 100644 index 000000000..8a1911323 --- /dev/null +++ b/docs/reference/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.html @@ -0,0 +1,149 @@ + + + + + + +slack_bolt.middleware.attaching_conversation_kwargs.attaching_conversation_kwargs API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.middleware.attaching_conversation_kwargs.attaching_conversation_kwargs

      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class AttachingConversationKwargs +(thread_context_store: AssistantThreadContextStore | None = None) +
      +
      +
      + +Expand source code + +
      class AttachingConversationKwargs(Middleware):
      +
      +    thread_context_store: Optional[AssistantThreadContextStore]
      +
      +    def __init__(self, thread_context_store: Optional[AssistantThreadContextStore] = None):
      +        self.thread_context_store = thread_context_store
      +
      +    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]:
      +        event = to_event(req.body)
      +        if event is not None:
      +            if is_assistant_event(req.body):
      +                assistant = AssistantUtilities(
      +                    payload=event,
      +                    context=req.context,
      +                    thread_context_store=self.thread_context_store,
      +                )
      +                req.context["say"] = assistant.say
      +                req.context["set_title"] = assistant.set_title
      +                req.context["set_suggested_prompts"] = assistant.set_suggested_prompts
      +                req.context["get_thread_context"] = assistant.get_thread_context
      +                req.context["save_thread_context"] = assistant.save_thread_context
      +
      +            # TODO: in the future we might want to introduce a "proper" extract_ts utility
      +            thread_ts = req.context.thread_ts or event.get("ts")
      +            if req.context.channel_id and thread_ts:
      +                req.context["set_status"] = SetStatus(
      +                    client=req.context.client,
      +                    channel_id=req.context.channel_id,
      +                    thread_ts=thread_ts,
      +                )
      +                req.context["say_stream"] = SayStream(
      +                    client=req.context.client,
      +                    channel=req.context.channel_id,
      +                    recipient_team_id=req.context.team_id or req.context.enterprise_id,
      +                    recipient_user_id=req.context.user_id,
      +                    thread_ts=thread_ts,
      +                )
      +        return next()
      +
      +

      A middleware can process request data before other middleware and listener functions.

      +

      Ancestors

      + +

      Class variables

      +
      +
      var thread_context_storeAssistantThreadContextStore | None
      +
      +

      The type of the None singleton.

      +
      +
      +

      Inherited members

      + +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/middleware/attaching_conversation_kwargs/index.html b/docs/reference/middleware/attaching_conversation_kwargs/index.html new file mode 100644 index 000000000..308a52712 --- /dev/null +++ b/docs/reference/middleware/attaching_conversation_kwargs/index.html @@ -0,0 +1,166 @@ + + + + + + +slack_bolt.middleware.attaching_conversation_kwargs API documentation + + + + + + + + + + + +
      +
      +
      +

      Module slack_bolt.middleware.attaching_conversation_kwargs

      +
      +
      +
      +
      +

      Sub-modules

      +
      +
      slack_bolt.middleware.attaching_conversation_kwargs.async_attaching_conversation_kwargs
      +
      +
      +
      +
      slack_bolt.middleware.attaching_conversation_kwargs.attaching_conversation_kwargs
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      Classes

      +
      +
      +class AttachingConversationKwargs +(thread_context_store: AssistantThreadContextStore | None = None) +
      +
      +
      + +Expand source code + +
      class AttachingConversationKwargs(Middleware):
      +
      +    thread_context_store: Optional[AssistantThreadContextStore]
      +
      +    def __init__(self, thread_context_store: Optional[AssistantThreadContextStore] = None):
      +        self.thread_context_store = thread_context_store
      +
      +    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]:
      +        event = to_event(req.body)
      +        if event is not None:
      +            if is_assistant_event(req.body):
      +                assistant = AssistantUtilities(
      +                    payload=event,
      +                    context=req.context,
      +                    thread_context_store=self.thread_context_store,
      +                )
      +                req.context["say"] = assistant.say
      +                req.context["set_title"] = assistant.set_title
      +                req.context["set_suggested_prompts"] = assistant.set_suggested_prompts
      +                req.context["get_thread_context"] = assistant.get_thread_context
      +                req.context["save_thread_context"] = assistant.save_thread_context
      +
      +            # TODO: in the future we might want to introduce a "proper" extract_ts utility
      +            thread_ts = req.context.thread_ts or event.get("ts")
      +            if req.context.channel_id and thread_ts:
      +                req.context["set_status"] = SetStatus(
      +                    client=req.context.client,
      +                    channel_id=req.context.channel_id,
      +                    thread_ts=thread_ts,
      +                )
      +                req.context["say_stream"] = SayStream(
      +                    client=req.context.client,
      +                    channel=req.context.channel_id,
      +                    recipient_team_id=req.context.team_id or req.context.enterprise_id,
      +                    recipient_user_id=req.context.user_id,
      +                    thread_ts=thread_ts,
      +                )
      +        return next()
      +
      +

      A middleware can process request data before other middleware and listener functions.

      +

      Ancestors

      + +

      Class variables

      +
      +
      var thread_context_storeAssistantThreadContextStore | None
      +
      +

      The type of the None singleton.

      +
      +
      +

      Inherited members

      + +
      +
      +
      +
      + +
      + + + diff --git a/docs/reference/middleware/index.html b/docs/reference/middleware/index.html index 05d773415..ce2629224 100644 --- a/docs/reference/middleware/index.html +++ b/docs/reference/middleware/index.html @@ -65,6 +65,10 @@

      Sub-modules

      +
      slack_bolt.middleware.attaching_conversation_kwargs
      +
      +
      +
      slack_bolt.middleware.attaching_function_token
      @@ -114,6 +118,76 @@

      Sub-modules

      Classes

      +
      +class AttachingConversationKwargs +(thread_context_store: AssistantThreadContextStore | None = None) +
      +
      +
      + +Expand source code + +
      class AttachingConversationKwargs(Middleware):
      +
      +    thread_context_store: Optional[AssistantThreadContextStore]
      +
      +    def __init__(self, thread_context_store: Optional[AssistantThreadContextStore] = None):
      +        self.thread_context_store = thread_context_store
      +
      +    def process(self, *, req: BoltRequest, resp: BoltResponse, next: Callable[[], BoltResponse]) -> Optional[BoltResponse]:
      +        event = to_event(req.body)
      +        if event is not None:
      +            if is_assistant_event(req.body):
      +                assistant = AssistantUtilities(
      +                    payload=event,
      +                    context=req.context,
      +                    thread_context_store=self.thread_context_store,
      +                )
      +                req.context["say"] = assistant.say
      +                req.context["set_title"] = assistant.set_title
      +                req.context["set_suggested_prompts"] = assistant.set_suggested_prompts
      +                req.context["get_thread_context"] = assistant.get_thread_context
      +                req.context["save_thread_context"] = assistant.save_thread_context
      +
      +            # TODO: in the future we might want to introduce a "proper" extract_ts utility
      +            thread_ts = req.context.thread_ts or event.get("ts")
      +            if req.context.channel_id and thread_ts:
      +                req.context["set_status"] = SetStatus(
      +                    client=req.context.client,
      +                    channel_id=req.context.channel_id,
      +                    thread_ts=thread_ts,
      +                )
      +                req.context["say_stream"] = SayStream(
      +                    client=req.context.client,
      +                    channel=req.context.channel_id,
      +                    recipient_team_id=req.context.team_id or req.context.enterprise_id,
      +                    recipient_user_id=req.context.user_id,
      +                    thread_ts=thread_ts,
      +                )
      +        return next()
      +
      +

      A middleware can process request data before other middleware and listener functions.

      +

      Ancestors

      + +

      Class variables

      +
      +
      var thread_context_storeAssistantThreadContextStore | None
      +
      +

      The type of the None singleton.

      +
      +
      +

      Inherited members

      + +
      class AttachingFunctionToken
      @@ -385,6 +459,7 @@

      Inherited members

      Subclasses

      Ancestors

      diff --git a/docs/reference/oauth/async_callback_options.html b/docs/reference/oauth/async_callback_options.html index 822867ea8..d07f1aee5 100644 --- a/docs/reference/oauth/async_callback_options.html +++ b/docs/reference/oauth/async_callback_options.html @@ -101,7 +101,7 @@

      Class variables

      reason: str, error: Optional[Exception] = None, suggested_status_code: int, - settings: "AsyncOAuthSettings", # type: ignore[name-defined] + settings: "AsyncOAuthSettings", default: "AsyncCallbackOptions", ): """The arguments for a failure function. @@ -153,7 +153,7 @@

      Args

      *, request: AsyncBoltRequest, installation: Installation, - settings: "AsyncOAuthSettings", # type: ignore[name-defined] + settings: "AsyncOAuthSettings", default: "AsyncCallbackOptions", ): """The arguments for a success function. diff --git a/docs/reference/oauth/async_oauth_settings.html b/docs/reference/oauth/async_oauth_settings.html index 3b8c04edb..5e6a543c4 100644 --- a/docs/reference/oauth/async_oauth_settings.html +++ b/docs/reference/oauth/async_oauth_settings.html @@ -48,7 +48,7 @@

      Classes

      class AsyncOAuthSettings -(*,
      client_id: str | None = None,
      client_secret: str | None = None,
      scopes: Sequence[str] | str | None = None,
      user_scopes: Sequence[str] | str | None = None,
      redirect_uri: str | None = None,
      install_path: str = '/slack/install',
      install_page_rendering_enabled: bool = True,
      redirect_uri_path: str = '/slack/oauth_redirect',
      callback_options: AsyncCallbackOptions | None = None,
      success_url: str | None = None,
      failure_url: str | None = None,
      authorization_url: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
      installation_store_bot_only: bool = False,
      token_rotation_expiration_minutes: int = 120,
      user_token_resolution: str = 'authed_user',
      state_validation_enabled: bool = True,
      state_store: slack_sdk.oauth.state_store.async_state_store.AsyncOAuthStateStore | None = None,
      state_cookie_name: str = 'slack-app-oauth-state',
      state_expiration_seconds: int = 600,
      logger: logging.Logger = <Logger slack_bolt.oauth.async_oauth_settings (WARNING)>)
      +(*,
      client_id: str | None = None,
      client_secret: str | None = None,
      scopes: str | Sequence[str] | None = None,
      user_scopes: str | Sequence[str] | None = None,
      redirect_uri: str | None = None,
      install_path: str = '/slack/install',
      install_page_rendering_enabled: bool = True,
      redirect_uri_path: str = '/slack/oauth_redirect',
      callback_options: AsyncCallbackOptions | None = None,
      success_url: str | None = None,
      failure_url: str | None = None,
      authorization_url: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.async_installation_store.AsyncInstallationStore | None = None,
      installation_store_bot_only: bool = False,
      token_rotation_expiration_minutes: int = 120,
      user_token_resolution: str = 'authed_user',
      state_validation_enabled: bool = True,
      state_store: slack_sdk.oauth.state_store.async_state_store.AsyncOAuthStateStore | None = None,
      state_cookie_name: str = 'slack-app-oauth-state',
      state_expiration_seconds: int = 600,
      logger: logging.Logger = <Logger slack_bolt.oauth.async_oauth_settings (WARNING)>)
      diff --git a/docs/reference/oauth/callback_options.html b/docs/reference/oauth/callback_options.html index 7ad3734b3..c6fc81286 100644 --- a/docs/reference/oauth/callback_options.html +++ b/docs/reference/oauth/callback_options.html @@ -181,7 +181,7 @@

      Inherited members

      reason: str, error: Optional[Exception] = None, suggested_status_code: int, - settings: "OAuthSettings", # type: ignore[name-defined] + settings: "OAuthSettings", default: "CallbackOptions", ): """The arguments for a failure function. @@ -233,7 +233,7 @@

      Args

      *, request: BoltRequest, installation: Installation, - settings: "OAuthSettings", # type: ignore[name-defined] + settings: "OAuthSettings", default: "CallbackOptions", ): """The arguments for a success function. diff --git a/docs/reference/oauth/oauth_settings.html b/docs/reference/oauth/oauth_settings.html index cd8def497..1eb2ab7dd 100644 --- a/docs/reference/oauth/oauth_settings.html +++ b/docs/reference/oauth/oauth_settings.html @@ -48,7 +48,7 @@

      Classes

      class OAuthSettings -(*,
      client_id: str | None = None,
      client_secret: str | None = None,
      scopes: Sequence[str] | str | None = None,
      user_scopes: Sequence[str] | str | None = None,
      redirect_uri: str | None = None,
      install_path: str = '/slack/install',
      install_page_rendering_enabled: bool = True,
      redirect_uri_path: str = '/slack/oauth_redirect',
      callback_options: CallbackOptions | None = None,
      success_url: str | None = None,
      failure_url: str | None = None,
      authorization_url: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
      installation_store_bot_only: bool = False,
      token_rotation_expiration_minutes: int = 120,
      user_token_resolution: str = 'authed_user',
      state_validation_enabled: bool = True,
      state_store: slack_sdk.oauth.state_store.state_store.OAuthStateStore | None = None,
      state_cookie_name: str = 'slack-app-oauth-state',
      state_expiration_seconds: int = 600,
      logger: logging.Logger = <Logger slack_bolt.oauth.oauth_settings (WARNING)>)
      +(*,
      client_id: str | None = None,
      client_secret: str | None = None,
      scopes: str | Sequence[str] | None = None,
      user_scopes: str | Sequence[str] | None = None,
      redirect_uri: str | None = None,
      install_path: str = '/slack/install',
      install_page_rendering_enabled: bool = True,
      redirect_uri_path: str = '/slack/oauth_redirect',
      callback_options: CallbackOptions | None = None,
      success_url: str | None = None,
      failure_url: str | None = None,
      authorization_url: str | None = None,
      installation_store: slack_sdk.oauth.installation_store.installation_store.InstallationStore | None = None,
      installation_store_bot_only: bool = False,
      token_rotation_expiration_minutes: int = 120,
      user_token_resolution: str = 'authed_user',
      state_validation_enabled: bool = True,
      state_store: slack_sdk.oauth.state_store.state_store.OAuthStateStore | None = None,
      state_cookie_name: str = 'slack-app-oauth-state',
      state_expiration_seconds: int = 600,
      logger: logging.Logger = <Logger slack_bolt.oauth.oauth_settings (WARNING)>)
      diff --git a/docs/reference/request/internals.html b/docs/reference/request/internals.html index bc13932ec..bd8319183 100644 --- a/docs/reference/request/internals.html +++ b/docs/reference/request/internals.html @@ -268,12 +268,12 @@

      Functions

      return channel.get("id") if "channel_id" in payload: return payload.get("channel_id") - if payload.get("event") is not None: + if isinstance(payload.get("event"), dict): return extract_channel_id(payload["event"]) - if payload.get("item") is not None: + if isinstance(payload.get("item"), dict): # reaction_added: body["event"]["item"] return extract_channel_id(payload["item"]) - if payload.get("assistant_thread") is not None: + if isinstance(payload.get("assistant_thread"), dict): # assistant_thread_started return extract_channel_id(payload["assistant_thread"]) return None @@ -317,10 +317,10 @@

      Functions

      return extract_enterprise_id(payload["authorizations"][0]) if "enterprise_id" in payload: return payload.get("enterprise_id") - if payload.get("team") is not None and "enterprise_id" in payload["team"]: + if isinstance(payload.get("team"), dict) and "enterprise_id" in payload["team"]: # In the case where the type is view_submission return payload["team"].get("enterprise_id") - if payload.get("event") is not None: + if isinstance(payload.get("event"), dict): return extract_enterprise_id(payload["event"]) return None
      @@ -337,7 +337,7 @@

      Functions

      def extract_function_bot_access_token(payload: Dict[str, Any]) -> Optional[str]:
           if payload.get("bot_access_token") is not None:
               return payload.get("bot_access_token")
      -    if payload.get("event") is not None:
      +    if isinstance(payload.get("event"), dict):
               return payload["event"].get("bot_access_token")
           return None
      @@ -354,9 +354,9 @@

      Functions

      def extract_function_execution_id(payload: Dict[str, Any]) -> Optional[str]:
           if payload.get("function_execution_id") is not None:
               return payload.get("function_execution_id")
      -    if payload.get("event") is not None:
      +    if isinstance(payload.get("event"), dict):
               return extract_function_execution_id(payload["event"])
      -    if payload.get("function_data") is not None:
      +    if isinstance(payload.get("function_data"), dict):
               return payload["function_data"].get("execution_id")
           return None
      @@ -371,9 +371,9 @@

      Functions

      Expand source code
      def extract_function_inputs(payload: Dict[str, Any]) -> Optional[Dict[str, Any]]:
      -    if payload.get("event") is not None:
      +    if isinstance(payload.get("event"), dict):
               return payload["event"].get("inputs")
      -    if payload.get("function_data") is not None:
      +    if isinstance(payload.get("function_data"), dict):
               return payload["function_data"].get("inputs")
           return None
      @@ -408,13 +408,13 @@

      Functions

      Expand source code
      def extract_team_id(payload: Dict[str, Any]) -> Optional[str]:
      -    app_installed_team_id = payload.get("view", {}).get("app_installed_team_id")
      -    if app_installed_team_id is not None:
      +    view = payload.get("view")
      +    if isinstance(view, dict) and view.get("app_installed_team_id") is not None:
               # view_submission payloads can have `view.app_installed_team_id` when a modal view that was opened
               # in a different workspace via some operations inside a Slack Connect channel.
               # Note that the same for enterprise_id does not exist. When you need to know the enterprise_id as well,
               # you have to run some query toward your InstallationStore to know the org where the team_id belongs to.
      -        return app_installed_team_id
      +        return view["app_installed_team_id"]
           if payload.get("team") is not None:
               # With org-wide installations, payload.team in interactivity payloads can be None
               # You need to extract either payload.user.team_id or payload.view.team_id as below
      @@ -429,12 +429,12 @@ 

      Functions

      return extract_team_id(payload["authorizations"][0]) if "team_id" in payload: return payload.get("team_id") - if payload.get("event") is not None: + if isinstance(payload.get("event"), dict): return extract_team_id(payload["event"]) - if payload.get("user") is not None: + if isinstance(payload.get("user"), dict): return payload["user"]["team_id"] - if payload.get("view") is not None: - return payload.get("view", {})["team_id"] + if isinstance(payload.get("view"), dict): + return payload["view"]["team_id"] return None
      @@ -448,30 +448,17 @@

      Functions

      Expand source code
      def extract_thread_ts(payload: Dict[str, Any]) -> Optional[str]:
      -    # This utility initially supports only the use cases for AI assistants, but it may be fine to add more patterns.
      -    # That said, note that thread_ts is always required for assistant threads, but it's not for channels.
      -    # Thus, blindly setting this thread_ts to say utility can break existing apps' behaviors.
      -    if is_assistant_event(payload):
      -        event = payload["event"]
      -        if (
      -            event.get("assistant_thread") is not None
      -            and event["assistant_thread"].get("channel_id") is not None
      -            and event["assistant_thread"].get("thread_ts") is not None
      -        ):
      -            # assistant_thread_started, assistant_thread_context_changed
      -            # "assistant_thread" property can exist for message event without channel_id and thread_ts
      -            # Thus, the above if check verifies these properties exist
      -            return event["assistant_thread"]["thread_ts"]
      -        elif event.get("channel") is not None:
      -            if event.get("thread_ts") is not None:
      -                # message in an assistant thread
      -                return event["thread_ts"]
      -            elif event.get("message", {}).get("thread_ts") is not None:
      -                # message_changed
      -                return event["message"]["thread_ts"]
      -            elif event.get("previous_message", {}).get("thread_ts") is not None:
      -                # message_deleted
      -                return event["previous_message"]["thread_ts"]
      +    thread_ts = payload.get("thread_ts")
      +    if thread_ts is not None:
      +        return thread_ts
      +    if isinstance(payload.get("event"), dict):
      +        return extract_thread_ts(payload["event"])
      +    if isinstance(payload.get("assistant_thread"), dict):
      +        return extract_thread_ts(payload["assistant_thread"])
      +    if isinstance(payload.get("message"), dict):
      +        return extract_thread_ts(payload["message"])
      +    if isinstance(payload.get("previous_message"), dict):
      +        return extract_thread_ts(payload["previous_message"])
           return None
      @@ -493,12 +480,12 @@

      Functions

      return user.get("id") if "user_id" in payload: return payload.get("user_id") - if payload.get("event") is not None: + if isinstance(payload.get("event"), dict): return extract_user_id(payload["event"]) - if payload.get("message") is not None: + if isinstance(payload.get("message"), dict): # message_changed: body["event"]["message"] return extract_user_id(payload["message"]) - if payload.get("previous_message") is not None: + if isinstance(payload.get("previous_message"), dict): # message_deleted: body["event"]["previous_message"] return extract_user_id(payload["previous_message"]) return None diff --git a/slack_bolt/version.py b/slack_bolt/version.py index 9b1349aea..ebda7dafb 100644 --- a/slack_bolt/version.py +++ b/slack_bolt/version.py @@ -1,3 +1,3 @@ """Check the latest version at https://pypi.org/project/slack-bolt/""" -__version__ = "1.27.0" +__version__ = "1.28.0" From 7e9b08bf636c7b2193a2fe5da277a5e7f2c5fd8f Mon Sep 17 00:00:00 2001 From: Luke Russell <31357343+lukegalbraithrussell@users.noreply.github.com> Date: Fri, 10 Apr 2026 11:23:22 -0700 Subject: [PATCH 6/7] docs: agent kit (#1478) Co-authored-by: William Bergamin Co-authored-by: Tracy Rericha <108959677+technically-tracy@users.noreply.github.com> Co-authored-by: William Bergamin --- docs/english/_sidebar.json | 21 +- .../english/concepts/adding-agent-features.md | 746 ++++++++++++++++++ docs/english/concepts/message-sending.md | 75 +- ...i-apps.md => using-the-assistant-class.md} | 201 +---- ...{building-an-app.md => creating-an-app.md} | 6 +- docs/english/experiments.md | 4 - docs/english/getting-started.md | 51 +- .../english/tutorial/ai-chatbot/ai-chatbot.md | 134 ++-- docs/japanese/concepts/assistant.md | 227 ------ 9 files changed, 892 insertions(+), 573 deletions(-) create mode 100644 docs/english/concepts/adding-agent-features.md rename docs/english/concepts/{ai-apps.md => using-the-assistant-class.md} (66%) rename docs/english/{building-an-app.md => creating-an-app.md} (99%) delete mode 100644 docs/japanese/concepts/assistant.md diff --git a/docs/english/_sidebar.json b/docs/english/_sidebar.json index eab9d94f8..79721bdcd 100644 --- a/docs/english/_sidebar.json +++ b/docs/english/_sidebar.json @@ -7,7 +7,19 @@ }, "tools/bolt-python/getting-started", { "type": "html", "value": "
      " }, - "tools/bolt-python/building-an-app", + "tools/bolt-python/creating-an-app", + { + "type": "category", + "label": "AI & Agents", + "link": { + "type": "doc", + "id": "tools/bolt-python/concepts/adding-agent-features" + }, + "items": [ + "tools/bolt-python/concepts/adding-agent-features", + "tools/bolt-python/concepts/using-the-assistant-class" + ] + }, { "type": "category", "label": "Slack API calls", @@ -39,7 +51,6 @@ "tools/bolt-python/concepts/app-home" ] }, - "tools/bolt-python/concepts/ai-apps", { "type": "category", "label": "Custom Steps", @@ -85,11 +96,7 @@ "tools/bolt-python/concepts/token-rotation" ] }, - { - "type": "category", - "label": "Experiments", - "items": ["tools/bolt-python/experiments"] - }, + "tools/bolt-python/experiments", { "type": "category", "label": "Legacy", diff --git a/docs/english/concepts/adding-agent-features.md b/docs/english/concepts/adding-agent-features.md new file mode 100644 index 000000000..cbd164630 --- /dev/null +++ b/docs/english/concepts/adding-agent-features.md @@ -0,0 +1,746 @@ +--- +sidebar_label: Adding agent features +--- + +# Adding agent features with Bolt for Python + +:::tip[Check out the Support Agent sample app] +The code snippets throughout this guide are from our [Support Agent sample app](https://github.com/slack-samples/bolt-python-support-agent), Casey, which supports integration with Pydantic, Anthropic, and OpenAI. + +View our [agent quickstart](/ai/agent-quickstart) to get up and running with Casey. Otherwise, read on for exploration and explanation of agent-focused Bolt features found within Casey. +::: + +Your agent can utilize features applicable to messages throughout Slack, like [chat streaming](#text-streaming) and [feedback buttons](#adding-and-handling-feedback). They can also [utilize the `Assistant` class](/tools/bolt-python/concepts/assistant-class) for a side-panel view designed with AI in mind. + +If you're unfamiliar with using these feature within Slack, you may want to read the [API docs on the subject](/ai/). Then come back here to implement them with Bolt! + +--- + +## Slack MCP Server {#slack-mcp-server} + +Casey can harness the [Slack MCP Server](https://docs.slack.dev/ai/slack-mcp-server/developing) when deployed via an HTTP Server with OAuth. + +To enable the Slack MCP Server: + +1. Install [ngrok](https://ngrok.com/download) and start a tunnel: + +```sh +ngrok http 3000 +``` + +2. Copy the `https://*.ngrok-free.app` URL from the ngrok output. + +3. Update `manifest.json` for HTTP mode: + - Set `socket_mode_enabled` to `false` + - Replace `ngrok-free.app` with your ngrok domain (e.g. `YOUR_NGROK_SUBDOMAIN.ngrok-free.app`) + +4. Create a new local dev app: + +```sh +slack install -E local +``` + +5. Enable MCP for your app: + - Run `slack app settings` to open your app's settings + - Navigate to **Agents & AI Apps** in the left-side navigation + - Toggle **Model Context Protocol** on + +6. Update your `.env` OAuth environment variables: + - Run `slack app settings` to open App Settings + - Copy **Client ID**, **Client Secret**, and **Signing Secret** + - Update `SLACK_REDIRECT_URI` in `.env` with your ngrok domain + +```sh +SLACK_CLIENT_ID=YOUR_CLIENT_ID +SLACK_CLIENT_SECRET=YOUR_CLIENT_SECRET +SLACK_REDIRECT_URI=https://YOUR_NGROK_SUBDOMAIN.ngrok-free.app/slack/oauth_redirect +SLACK_SIGNING_SECRET=YOUR_SIGNING_SECRET +``` + +7. Start the app: + +```sh +slack run app_oauth.py +``` + +8. Click the install URL printed in the terminal to install the app to your workspace via OAuth. + +Your agent can now access the Slack MCP server! + +--- + +## Listening for user invocation + +Agents can be invoked throughout Slack, such as via @mentions in channels, messaging the agent, and using the assistant side panel. + + + + +```python +import re +from logging import Logger + +from agents import Runner +from slack_bolt import BoltContext, Say, SayStream, SetStatus +from slack_sdk import WebClient + +from agent import CaseyDeps, casey_agent +from thread_context import conversation_store +from listeners.views.feedback_builder import build_feedback_blocks + + +def handle_app_mentioned( + client: WebClient, + context: BoltContext, + event: dict, + logger: Logger, + say: Say, + say_stream: SayStream, + set_status: SetStatus, +): + """Handle @Casey mentions in channels.""" + try: + channel_id = context.channel_id + text = event.get("text", "") + thread_ts = event.get("thread_ts") or event["ts"] + user_id = context.user_id + + # Strip the bot mention from the text + cleaned_text = re.sub(r"<@[A-Z0-9]+>", "", text).strip() + + if not cleaned_text: + say( + text="Hey there! How can I help you? Describe your IT issue and I'll do my best to assist.", + thread_ts=thread_ts, + ) + return + + # Add eyes reaction only to the first message (not threaded replies) + if not event.get("thread_ts"): + client.reactions_add( + channel=channel_id, + timestamp=event["ts"], + name="eyes", + ) + ... +``` + + + + +```python +from logging import Logger + +from slack_bolt.context import BoltContext +from slack_bolt.context.say import Say +from slack_bolt.context.say_stream import SayStream +from slack_bolt.context.set_status import SetStatus +from slack_sdk import WebClient + +from agent import CaseyDeps, run_casey_agent +from thread_context import session_store +from listeners.views.feedback_builder import build_feedback_blocks + + +def handle_message( + client: WebClient, + context: BoltContext, + event: dict, + logger: Logger, + say: Say, + say_stream: SayStream, + set_status: SetStatus, +): + """Handle messages sent to Casey via DM or in threads the bot is part of.""" + # Issue submissions are posted by the bot with metadata so the message + # handler can run the agent on behalf of the original user. + is_issue_submission = ( + event.get("metadata", {}).get("event_type") == "issue_submission" + ) + + # Skip message subtypes (edits, deletes, etc.) and bot messages that + # are not issue submissions. + if event.get("subtype"): + return + if event.get("bot_id") and not is_issue_submission: + return + + is_dm = event.get("channel_type") == "im" + is_thread_reply = event.get("thread_ts") is not None + + if is_dm: + pass + elif is_thread_reply: + # Channel thread replies are handled only if the bot is already engaged + session = session_store.get_session(context.channel_id, event["thread_ts"]) + if session is None: + return + else: + # Top-level channel messages are handled by app_mentioned + return + + try: + channel_id = context.channel_id + text = event.get("text", "") + thread_ts = event.get("thread_ts") or event["ts"] + + # Get session ID for conversation context + existing_session_id = session_store.get_session(channel_id, thread_ts) + + # Add eyes reaction only to the first message (DMs only — channel + # threads already have the reaction from the initial app_mention) + if is_dm and not existing_session_id: + await client.reactions_add( + channel=channel_id, + timestamp=event["ts"], + name="eyes", + ) + + ... +``` + + + + + +:::tip[Using the Assistant side panel] +The Assistant side panel requires additional setup. See the [Assistant class guide](/tools/bolt-python/concepts/assistant-class). +::: + + +```py +from logging import Logger + +from slack_bolt.context.set_suggested_prompts import SetSuggestedPrompts + +SUGGESTED_PROMPTS = [ + {"title": "Reset Password", "message": "I need to reset my password"}, + {"title": "Request Access", "message": "I need access to a system or tool"}, + {"title": "Network Issues", "message": "I'm having network connectivity issues"}, +] + + +def handle_assistant_thread_started( + set_suggested_prompts: SetSuggestedPrompts, logger: Logger +): + """Handle assistant thread started events by setting suggested prompts.""" + try: + set_suggested_prompts( + prompts=SUGGESTED_PROMPTS, + title="How can I help you today?", + ) + except Exception as e: + logger.exception(f"Failed to handle assistant thread started: {e}") +``` + + + + +--- + +## Setting status {#setting-assistant-status} + +Your app can show actions are happening behind the scenes by setting its thread status. + +```python +def handle_app_mentioned( + set_status: SetStatus, + ... +): + set_status( + status="Thinking...", + loading_messages=[ + "Teaching the hamsters to type faster…", + "Untangling the internet cables…", + "Consulting the office goldfish…", + "Polishing up the response just for you…", + "Convincing the AI to stop overthinking…", + ], + ) +``` + +--- + +## Streaming messages {#text-streaming} + +You can have your app's messages stream in to replicate conventional agent behavior. Bolt for Python provides a `say_stream` utility as a listener argument available for `app.event` and `app.message` listeners. + +The `say_stream` utility streamlines calling the Python Slack SDK's [`WebClient.chat_stream`](https://docs.slack.dev/tools/python-slack-sdk/reference/web/client.html#slack_sdk.web.client.WebClient.chat_stream) helper utility by sourcing parameter values from the relevant event payload. + +| Parameter | Value | +|---|---| +| `channel_id` | Sourced from the event payload. +| `thread_ts` | Sourced from the event payload. Falls back to the `ts` value if available. +| `recipient_team_id` | Sourced from the event `team_id` (`enterprise_id` if the app is installed on an org). +| `recipient_user_id` | Sourced from the `user_id` of the event. + +If neither a `channel_id` or `thread_ts` can be sourced, then the utility will be `None`. + +```python +streamer = say_stream() +streamer.append(markdown_text="Here's my response...") +streamer.append(markdown_text="And here's more...") +streamer.stop() +``` + +--- + +## Adding and handling feedback {#adding-and-handling-feedback} + +You can use the [feedback buttons block element](/reference/block-kit/block-elements/feedback-buttons-element/) to allow users to immediately provide feedback regarding the app's responses. Here's what the feedback buttons look like from the Support Agent sample app: + +```py title=".../listeners/views/feedback_builder.py" +from slack_sdk.models.blocks import ( + Block, + ContextActionsBlock, + FeedbackButtonObject, + FeedbackButtonsElement, +) + + +def build_feedback_blocks() -> list[Block]: + """Build feedback blocks with thumbs up/down buttons.""" + return [ + ContextActionsBlock( + elements=[ + FeedbackButtonsElement( + action_id="feedback", + positive_button=FeedbackButtonObject( + text="Good Response", + accessibility_label="Submit positive feedback on this response", + value="good-feedback", + ), + negative_button=FeedbackButtonObject( + text="Bad Response", + accessibility_label="Submit negative feedback on this response", + value="bad-feedback", + ), + ) + ] + ) + ] +``` + +That feedback block is then rendered at the bottom of your app's message via the `say_stream` utility. + +```py +... + # Stream response in thread with feedback buttons + streamer = say_stream() + streamer.append(markdown_text=result.output) + feedback_blocks = build_feedback_blocks() + streamer.stop(blocks=feedback_blocks) +... +``` + +You can also add a response for when the user provides feedback. + +```python title="...listeners/actions/feedback_button.py" +from logging import Logger + +from slack_bolt import Ack, BoltContext +from slack_sdk import WebClient + + +def handle_feedback_button( + ack: Ack, body: dict, client: WebClient, context: BoltContext, logger: Logger +): + """Handle thumbs up/down feedback on Casey's responses.""" + ack() + + try: + channel_id = context.channel_id + user_id = context.user_id + message_ts = body["message"]["ts"] + feedback_value = body["actions"][0]["value"] + + if feedback_value == "good-feedback": + client.chat_postEphemeral( + channel=channel_id, + user=user_id, + thread_ts=message_ts, + text="Glad that was helpful! :tada:", + ) + else: + client.chat_postEphemeral( + channel=channel_id, + user=user_id, + thread_ts=message_ts, + text="Sorry that wasn't helpful. :slightly_frowning_face: Try rephrasing your question or I can create a support ticket for you.", + ) + + logger.debug( + f"Feedback received: value={feedback_value}, message_ts={message_ts}" + ) + except Exception as e: + logger.exception(f"Failed to handle feedback: {e}") +``` + +--- + +## Full example + +Putting all those concepts together results in a dynamic agent ready to helpfully respond. + + +
      +Full example + + + +```python title="app_mentioned.py" +import re +from logging import Logger + +from slack_bolt import BoltContext, Say, SayStream, SetStatus +from slack_sdk import WebClient + +from agent import CaseyDeps, casey_agent, get_model +from thread_context import conversation_store +from listeners.views.feedback_builder import build_feedback_blocks + + +def handle_app_mentioned( + client: WebClient, + context: BoltContext, + event: dict, + logger: Logger, + say: Say, + say_stream: SayStream, + set_status: SetStatus, +): + """Handle @Casey mentions in channels.""" + try: + channel_id = context.channel_id + text = event.get("text", "") + thread_ts = event.get("thread_ts") or event["ts"] + user_id = context.user_id + + # Strip the bot mention from the text + cleaned_text = re.sub(r"<@[A-Z0-9]+>", "", text).strip() + + if not cleaned_text: + say( + text="Hey there! How can I help you? Describe your IT issue and I'll do my best to assist.", + thread_ts=thread_ts, + ) + return + + # Add eyes reaction only to the first message (not threaded replies) + if not event.get("thread_ts"): + client.reactions_add( + channel=channel_id, + timestamp=event["ts"], + name="eyes", + ) + + # Set assistant thread status with loading messages + set_status( + status="Thinking...", + loading_messages=[ + "Teaching the hamsters to type faster…", + "Untangling the internet cables…", + "Consulting the office goldfish…", + "Polishing up the response just for you…", + "Convincing the AI to stop overthinking…", + ], + ) + + # Get conversation history + history = conversation_store.get_history(channel_id, thread_ts) + + # Run the agent + deps = CaseyDeps( + client=client, + user_id=user_id, + channel_id=channel_id, + thread_ts=thread_ts, + message_ts=event["ts"], + ) + result = casey_agent.run_sync( + cleaned_text, + model=get_model(), + deps=deps, + message_history=history, + ) + + # Stream response in thread with feedback buttons + streamer = say_stream() + streamer.append(markdown_text=result.output) + feedback_blocks = build_feedback_blocks() + streamer.stop(blocks=feedback_blocks) + + # Store conversation history + conversation_store.set_history(channel_id, thread_ts, result.all_messages()) + + except Exception as e: + logger.exception(f"Failed to handle app mention: {e}") + say( + text=f":warning: Something went wrong! ({e})", + thread_ts=event.get("thread_ts") or event["ts"], + ) +``` + + + + +```python title="app_mentioned.py" +import re +from logging import Logger + +from slack_bolt.context import BoltContext +from slack_bolt.context.say import Say +from slack_bolt.context.say_stream import SayStream +from slack_bolt.context.set_status import SetStatus +from slack_sdk import WebClient + +from agent import CaseyDeps, run_casey_agent +from thread_context import session_store +from listeners.views.feedback_builder import build_feedback_blocks + + +def handle_app_mentioned( + client: WebClient, + context: BoltContext, + event: dict, + logger: Logger, + say: Say, + say_stream: SayStream, + set_status: SetStatus, +): + """Handle @Casey mentions in channels.""" + try: + channel_id = context.channel_id + text = event.get("text", "") + thread_ts = event.get("thread_ts") or event["ts"] + + # Strip the bot mention from the text + cleaned_text = re.sub(r"<@[A-Z0-9]+>", "", text).strip() + + if not cleaned_text: + say( + text="Hey there! How can I help you? Describe your IT issue and I'll do my best to assist.", + thread_ts=thread_ts, + ) + return + + # Add eyes reaction only to the first message (not threaded replies) + if not event.get("thread_ts"): + client.reactions_add( + channel=channel_id, + timestamp=event["ts"], + name="eyes", + ) + + # Set assistant thread status with loading messages + set_status( + status="Thinking...", + loading_messages=[ + "Teaching the hamsters to type faster…", + "Untangling the internet cables…", + "Consulting the office goldfish…", + "Polishing up the response just for you…", + "Convincing the AI to stop overthinking…", + ], + ) + + # Get session ID for conversation context + existing_session_id = session_store.get_session(channel_id, thread_ts) + + # Run the agent with deps for tool access + deps = CaseyDeps( + client=client, + user_id=context.user_id, + channel_id=channel_id, + thread_ts=thread_ts, + message_ts=event["ts"], + ) + response_text, new_session_id = run_casey_agent( + cleaned_text, session_id=existing_session_id, deps=deps + ) + + # Stream response in thread with feedback buttons + streamer = say_stream() + streamer.append(markdown_text=response_text) + feedback_blocks = build_feedback_blocks() + streamer.stop(blocks=feedback_blocks) + + # Store session ID for future context + if new_session_id: + session_store.set_session(channel_id, thread_ts, new_session_id) + + except Exception as e: + logger.exception(f"Failed to handle app mention: {e}") + await say( + text=f":warning: Something went wrong! ({e})", + thread_ts=event.get("thread_ts") or event["ts"], + ) +``` + + + +```python title="app_mentioned.py" +import re +from logging import Logger + +from agents import Runner +from slack_bolt import BoltContext, Say, SayStream, SetStatus +from slack_sdk import WebClient + +from agent import CaseyDeps, casey_agent +from thread_context import conversation_store +from listeners.views.feedback_builder import build_feedback_blocks + + +def handle_app_mentioned( + client: WebClient, + context: BoltContext, + event: dict, + logger: Logger, + say: Say, + say_stream: SayStream, + set_status: SetStatus, +): + """Handle @Casey mentions in channels.""" + try: + channel_id = context.channel_id + text = event.get("text", "") + thread_ts = event.get("thread_ts") or event["ts"] + user_id = context.user_id + + # Strip the bot mention from the text + cleaned_text = re.sub(r"<@[A-Z0-9]+>", "", text).strip() + + if not cleaned_text: + say( + text="Hey there! How can I help you? Describe your IT issue and I'll do my best to assist.", + thread_ts=thread_ts, + ) + return + + # Add eyes reaction only to the first message (not threaded replies) + if not event.get("thread_ts"): + client.reactions_add( + channel=channel_id, + timestamp=event["ts"], + name="eyes", + ) + + # Set assistant thread status with loading messages + set_status( + status="Thinking...", + loading_messages=[ + "Teaching the hamsters to type faster…", + "Untangling the internet cables…", + "Consulting the office goldfish…", + "Polishing up the response just for you…", + "Convincing the AI to stop overthinking…", + ], + ) + + # Get conversation history + history = conversation_store.get_history(channel_id, thread_ts) + + # Build input for the agent + if history: + input_items = history + [{"role": "user", "content": cleaned_text}] + else: + input_items = cleaned_text + + # Run the agent + deps = CaseyDeps( + client=client, + user_id=user_id, + channel_id=channel_id, + thread_ts=thread_ts, + message_ts=event["ts"], + ) + result = Runner.run_sync(casey_agent, input=input_items, context=deps) + + # Stream response in thread with feedback buttons + streamer = say_stream() + streamer.append(markdown_text=result.final_output) + feedback_blocks = build_feedback_blocks() + streamer.stop(blocks=feedback_blocks) + + # Store conversation history + conversation_store.set_history(channel_id, thread_ts, result.to_input_list()) + + except Exception as e: + logger.exception(f"Failed to handle app mention: {e}") + say( + text=f":warning: Something went wrong! ({e})", + thread_ts=event.get("thread_ts") or event["ts"], + ) +``` + + + +
      + +--- + +## Onward: adding custom tools + +Casey comes with test tools and simulated systems. You can extend it with custom tools to make it a fully functioning Slack agent. + +In this example, we'll add a tool that makes live calls to check the GitHub status. + +1. Create `agent/tools/{tool-name}.py` and define the tool with the `@tool` decorator: + +```python title="agent/tools/check_github_status.py" +from claude_agent_sdk import tool +import httpx + +@tool( + name="check_github_status", + description="Check GitHub's current operational status", + input_schema={}, +) +async def check_github_status_tool(args): + """Check if GitHub is operational.""" + async with httpx.AsyncClient() as client: + response = await client.get("https://www.githubstatus.com/api/v2/status.json") + data = response.json() + status = data["status"]["indicator"] + description = data["status"]["description"] + + return { + "content": [ + { + "type": "text", + "text": f"**GitHub Status** — {status}\n{description}", + } + ] + } +``` + +2. Import the tool in `agent/casey.py`: + +```python title="agent/casey.py" +from agent.tools import check_github_status_tool +``` + +3. Register in `casey_tools_server`: + +```python title="agent/casey.py" +casey_tools_server = create_sdk_mcp_server( + name="casey-tools", + version="1.0.0", + tools=[ + check_github_status_tool, # Add here + # ... other tools + ], +) +``` + +4. Add to `CASEY_TOOLS`: + +```python title="agent/casey.py" +CASEY_TOOLS = [ + "check_github_status", # Add here + # ... other tools +] +``` + +Use this example as a jumping off point for building out an agent with the capabilities you need! \ No newline at end of file diff --git a/docs/english/concepts/message-sending.md b/docs/english/concepts/message-sending.md index 87c433129..090503ff2 100644 --- a/docs/english/concepts/message-sending.md +++ b/docs/english/concepts/message-sending.md @@ -43,37 +43,58 @@ def show_datepicker(event, say): ## Streaming messages {#streaming-messages} -You can have your app's messages stream in to replicate conventional AI chatbot behavior. This is done through three Web API methods: +You can have your app's messages stream in to replicate conventional agent behavior. Bolt for Python provides a `say_stream` utility as a listener argument available for `app.event` and `app.message` listeners. -* [`chat_startStream`](/reference/methods/chat.startStream) -* [`chat_appendStream`](/reference/methods/chat.appendStream) -* [`chat_stopStream`](/reference/methods/chat.stopStream) +The `say_stream` utility streamlines calling the Python Slack SDK's [`WebClient.chat_stream`](https://docs.slack.dev/tools/python-slack-sdk/reference/web/client.html#slack_sdk.web.client.WebClient.chat_stream) helper utility by sourcing parameter values from the relevant event payload. -The Python Slack SDK provides a [`chat_stream()`](https://docs.slack.dev/tools/python-slack-sdk/reference/web/client.html#slack_sdk.web.client.WebClient.chat_stream) helper utility to streamline calling these methods. Here's an excerpt from our [Assistant template app](https://github.com/slack-samples/bolt-python-assistant-template): +| Parameter | Value | +|---|---| +| `channel_id` | Sourced from the event payload. +| `thread_ts` | Sourced from the event payload. Falls back to the `ts` value if available. +| `recipient_team_id` | Sourced from the event `team_id` (`enterprise_id` if the app is installed on an org). +| `recipient_user_id` | Sourced from the `user_id` of the event. -```python -streamer = client.chat_stream( - channel=channel_id, - recipient_team_id=team_id, - recipient_user_id=user_id, - thread_ts=thread_ts, -) - -# Loop over OpenAI response stream -# https://platform.openai.com/docs/api-reference/responses/create -for event in returned_message: - if event.type == "response.output_text.delta": - streamer.append(markdown_text=f"{event.delta}") - else: - continue - -feedback_block = create_feedback_block() -streamer.stop(blocks=feedback_block) +If neither a `channel_id` or `thread_ts` can be sourced, then the utility will be `None`. + +For information on calling the `chat_*Stream` API methods directly, see the [_Sending streaming messages_](/tools/python-slack-sdk/web#sending-streaming-messages) section of the Python Slack SDK docs. + +### Example {#example} + +```py +import os + +from slack_bolt import App, SayStream +from slack_bolt.adapter.socket_mode import SocketModeHandler +from slack_sdk import WebClient + +app = App(token=os.environ.get("SLACK_BOT_TOKEN")) + +@app.event("app_mention") +def handle_app_mention(client: WebClient, say_stream: SayStream): + stream = say_stream() + stream.append(markdown_text="Someone rang the bat signal!") + stream.stop() + +@app.message("") +def handle_message(client: WebClient, say_stream: SayStream): + stream = say_stream() + + stream.append(markdown_text="Let me consult my *vast knowledge database*...) + stream.stop() + +if __name__ == "__main__": + SocketModeHandler(app, os.environ.get("SLACK_APP_TOKEN")).start() ``` -In that example, a [feedback buttons](/reference/block-kit/block-elements/feedback-buttons-element) block element is passed to `streamer.stop` to provide feedback buttons to the user at the bottom of the message. Interaction with these buttons will send a block action event to your app to receive the feedback. +#### Adding feedback buttons after a stream -```python +You can pass a [feedback buttons](/reference/block-kit/block-elements/feedback-buttons-element) block element to `stream.stop` to provide feedback buttons to the user at the bottom of the message. Interaction with these buttons will send a block action event to your app to receive the feedback. + +```py +stream.stop(blocks=feedback_block) +``` + +```py def create_feedback_block() -> List[Block]: blocks: List[Block] = [ ContextActionsBlock( @@ -95,6 +116,4 @@ def create_feedback_block() -> List[Block]: ) ] return blocks -``` - -For information on calling the `chat_*Stream` API methods without the helper utility, see the [_Sending streaming messages_](/tools/python-slack-sdk/web#sending-streaming-messages) section of the Python Slack SDK docs. \ No newline at end of file +``` \ No newline at end of file diff --git a/docs/english/concepts/ai-apps.md b/docs/english/concepts/using-the-assistant-class.md similarity index 66% rename from docs/english/concepts/ai-apps.md rename to docs/english/concepts/using-the-assistant-class.md index 3b057bc7e..ed004dc35 100644 --- a/docs/english/concepts/ai-apps.md +++ b/docs/english/concepts/using-the-assistant-class.md @@ -1,17 +1,10 @@ - -# Using AI in Apps {#using-ai-in-apps} - -The Slack platform offers features tailored for AI agents and assistants. Your apps can [utilize the `Assistant` class](#assistant) for a side-panel view designed with AI in mind, or they can utilize features applicable to messages throughout Slack, like [chat streaming](#text-streaming) and [feedback buttons](#adding-and-handling-feedback). - -If you're unfamiliar with using these feature within Slack, you may want to read the [API documentation on the subject](/ai/). Then come back here to implement them with Bolt! - -## The `Assistant` class instance {#assistant} +# Using the Assistant class :::info[Some features within this guide require a paid plan] If you don't have a paid workspace for development, you can join the [Developer Program](https://api.slack.com/developer-program) and provision a sandbox with access to all Slack features for free. ::: -The [`Assistant`](/tools/bolt-js/reference#the-assistantconfig-configuration-object) class can be used to handle the incoming events expected from a user interacting with an app in Slack that has the Agents & AI Apps feature enabled. +The `Assistant` class can be used to handle the incoming events expected from a user interacting with an app in Slack that has the Agents & AI Apps feature enabled. A typical flow would look like: @@ -63,7 +56,7 @@ If you do provide your own `threadContextStore` property, it must feature `get` :::tip[Refer to the [reference docs](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html) to learn the available listener arguments.] ::: -### Configuring your app to support the `Assistant` class {#configuring-assistant-class} +## Configuring your app to support the `Assistant` class {#configuring-assistant-class} 1. Within [App Settings](https://api.slack.com/apps), enable the **Agents & AI Apps** feature. @@ -77,7 +70,7 @@ If you do provide your own `threadContextStore` property, it must feature `get` * [`assistant_thread_context_changed`](/reference/events/assistant_thread_context_changed) * [`message.im`](/reference/events/message.im) -### Handling a new thread {#handling-new-thread} +## Handling a new thread {#handling-new-thread} When the user opens a new thread with your AI-enabled app, the [`assistant_thread_started`](/reference/events/assistant_thread_started) event will be sent to your app. @@ -122,7 +115,7 @@ def start_assistant_thread( You can send more complex messages to the user — see [Sending Block Kit alongside messages](#block-kit-interactions) for more info. -### Handling thread context changes {#handling-thread-context-changes} +## Handling thread context changes {#handling-thread-context-changes} When the user switches channels, the [`assistant_thread_context_changed`](/reference/events/assistant_thread_context_changed) event will be sent to your app. @@ -137,7 +130,7 @@ from slack_bolt import FileAssistantThreadContextStore assistant = Assistant(thread_context_store=FileAssistantThreadContextStore()) ``` -### Handling the user response {#handling-user-response} +## Handling the user response {#handling-user-response} When the user messages your app, the [`message.im`](/reference/events/message.im) event will be sent to your app. @@ -205,7 +198,7 @@ def respond_in_assistant_thread( app.use(assistant) ``` -### Sending Block Kit alongside messages {#block-kit-interactions} +## Sending Block Kit alongside messages {#block-kit-interactions} For advanced use cases, Block Kit buttons may be used instead of suggested prompts, as well as the sending of messages with structured [metadata](/messaging/message-metadata/) to trigger subsequent interactions with the user. @@ -331,182 +324,6 @@ def respond_to_bot_messages(logger: logging.Logger, set_status: SetStatus, say: ... ``` -See the [_Adding and handling feedback_](#adding-and-handling-feedback) section for adding feedback buttons with Block Kit. - -## Text streaming in messages {#text-streaming} - -Three Web API methods work together to provide users a text streaming experience: - -* the [`chat.startStream`](/reference/methods/chat.startStream) method starts the text stream, -* the [`chat.appendStream`](/reference/methods/chat.appendStream) method appends text to the stream, and -* the [`chat.stopStream`](/reference/methods/chat.stopStream) method stops it. - -Since you're using Bolt for Python, built upon the Python Slack SDK, you can use the [`chat_stream()`](https://docs.slack.dev/tools/python-slack-sdk/reference/web/client.html#slack_sdk.web.client.WebClient.chat_stream) utility to streamline all three aspects of streaming in your app's messages. - -The following example uses OpenAI's streaming API with the new `chat_stream()` functionality, but you can substitute it with the AI client of your choice. - - -```python -import os -from typing import List, Dict - -import openai -from openai import Stream -from openai.types.responses import ResponseStreamEvent - -DEFAULT_SYSTEM_CONTENT = """ -You're an assistant in a Slack workspace. -Users in the workspace will ask you to help them write something or to think better about a specific topic. -You'll respond to those questions in a professional way. -When you include markdown text, convert them to Slack compatible ones. -When a prompt has Slack's special syntax like <@USER_ID> or <#CHANNEL_ID>, you must keep them as-is in your response. -""" - -def call_llm( - messages_in_thread: List[Dict[str, str]], - system_content: str = DEFAULT_SYSTEM_CONTENT, -) -> Stream[ResponseStreamEvent]: - openai_client = openai.OpenAI(api_key=os.getenv("OPENAI_API_KEY")) - messages = [{"role": "system", "content": system_content}] - messages.extend(messages_in_thread) - response = openai_client.responses.create(model="gpt-4o-mini", input=messages, stream=True) - return response - -@assistant.user_message -def respond_in_assistant_thread( - ... -): - try: - ... - replies = client.conversations_replies( - channel=context.channel_id, - ts=context.thread_ts, - oldest=context.thread_ts, - limit=10, - ) - messages_in_thread: List[Dict[str, str]] = [] - for message in replies["messages"]: - role = "user" if message.get("bot_id") is None else "assistant" - messages_in_thread.append({"role": role, "content": message["text"]}) - - returned_message = call_llm(messages_in_thread) - - streamer = client.chat_stream( - channel=channel_id, - recipient_team_id=team_id, - recipient_user_id=user_id, - thread_ts=thread_ts, - ) - - # Loop over OpenAI response stream - # https://platform.openai.com/docs/api-reference/responses/create - for event in returned_message: - if event.type == "response.output_text.delta": - streamer.append(markdown_text=f"{event.delta}") - else: - continue - - streamer.stop() - - except Exception as e: - logger.exception(f"Failed to handle a user message event: {e}") - say(f":warning: Something went wrong! ({e})") -``` - -## Adding and handling feedback {#adding-and-handling-feedback} - -Use the [feedback buttons block element](/reference/block-kit/block-elements/feedback-buttons-element/) to allow users to immediately provide feedback regarding your app's responses. Here's a quick example: - -```py -from typing import List -from slack_sdk.models.blocks import Block, ContextActionsBlock, FeedbackButtonsElement, FeedbackButtonObject - - -def create_feedback_block() -> List[Block]: - """ - Create feedback block with thumbs up/down buttons - - Returns: - Block Kit context_actions block - """ - blocks: List[Block] = [ - ContextActionsBlock( - elements=[ - FeedbackButtonsElement( - action_id="feedback", - positive_button=FeedbackButtonObject( - text="Good Response", - accessibility_label="Submit positive feedback on this response", - value="good-feedback", - ), - negative_button=FeedbackButtonObject( - text="Bad Response", - accessibility_label="Submit negative feedback on this response", - value="bad-feedback", - ), - ) - ] - ) - ] - return blocks -``` - -Use the `chat_stream` utility to render the feedback block at the bottom of your app's message. - -```js -... - streamer = client.chat_stream( - channel=channel_id, - recipient_team_id=team_id, - recipient_user_id=user_id, - thread_ts=thread_ts, - ) - - # Loop over OpenAI response stream - # https://platform.openai.com/docs/api-reference/responses/create - for event in returned_message: - if event.type == "response.output_text.delta": - streamer.append(markdown_text=f"{event.delta}") - else: - continue - - feedback_block = create_feedback_block() - streamer.stop(blocks=feedback_block) -... -``` - -Then add a response for when the user provides feedback. - -```python -# Handle feedback buttons (thumbs up/down) -def handle_feedback(ack, body, client, logger: logging.Logger): - try: - ack() - message_ts = body["message"]["ts"] - channel_id = body["channel"]["id"] - feedback_type = body["actions"][0]["value"] - is_positive = feedback_type == "good-feedback" - - if is_positive: - client.chat_postEphemeral( - channel=channel_id, - user=body["user"]["id"], - thread_ts=message_ts, - text="We're glad you found this useful.", - ) - else: - client.chat_postEphemeral( - channel=channel_id, - user=body["user"]["id"], - thread_ts=message_ts, - text="Sorry to hear that response wasn't up to par :slightly_frowning_face: Starting a new chat may help with AI mistakes and hallucinations.", - ) - - logger.debug(f"Handled feedback: type={feedback_type}, message_ts={message_ts}") - except Exception as error: - logger.error(f":warning: Something went wrong! {error}") -``` - -## Full example: App Agent Template {#app-agent-template} +See the [_Creating agents: adding and handling feedback_](/tools/bolt-python/concepts/adding-agent-features#adding-and-handling-feedback) section for adding feedback buttons with Block Kit. -Want to see the functionality described throughout this guide in action? We've created a [App Agent Template](https://github.com/slack-samples/bolt-python-assistant-template) repo for you to build off of. +Want to see the functionality described throughout this guide in action? We've created a [App Agent Template](https://github.com/slack-samples/bolt-python-assistant-template) repo for you to build from. \ No newline at end of file diff --git a/docs/english/building-an-app.md b/docs/english/creating-an-app.md similarity index 99% rename from docs/english/building-an-app.md rename to docs/english/creating-an-app.md index bde340961..7f06e9d42 100644 --- a/docs/english/building-an-app.md +++ b/docs/english/creating-an-app.md @@ -1,8 +1,8 @@ --- -sidebar_label: Building an App +sidebar_label: Creating an app --- -# Building an App with Bolt for Python +# Creating an app with Bolt for Python This guide is meant to walk you through getting up and running with a Slack app using Bolt for Python. Along the way, we’ll create a new Slack app, set up your local environment, and develop an app that listens and responds to messages from a Slack workspace. @@ -10,7 +10,7 @@ When you're finished, you'll have created the [Getting Started app](https://gith --- -### Create an app {#create-an-app} +### Create a new app {#create-an-app} First thing's first: before you start developing with Bolt, you'll want to [create a Slack app](https://api.slack.com/apps/new). :::tip[A place to test and learn] diff --git a/docs/english/experiments.md b/docs/english/experiments.md index 681c8cbc6..13adf0a32 100644 --- a/docs/english/experiments.md +++ b/docs/english/experiments.md @@ -28,7 +28,3 @@ def handle_mention(agent: BoltAgent): stream.append(markdown_text="Hello!") stream.stop() ``` - -### Limitations - -The `chat_stream()` method currently only works when the `thread_ts` field is available in the event context (DMs and threaded replies). Top-level channel messages do not have a `thread_ts` field, and the `ts` field is not yet provided to `BoltAgent`. \ No newline at end of file diff --git a/docs/english/getting-started.md b/docs/english/getting-started.md index 934dd3bae..6964df23b 100644 --- a/docs/english/getting-started.md +++ b/docs/english/getting-started.md @@ -279,55 +279,10 @@ This will open the following page: On these pages you're free to make changes such as updating your app icon, configuring app features, and perhaps even distributing your app! -## Adding AI features {#ai-features} - -Now that you're familiar with a basic app setup, try it out again, this time using the AI agent template! - - - - -Get started with the agent template: - -```sh -$ slack create ai-app --template slack-samples/bolt-python-assistant-template -$ cd ai-app -``` - - - - -Get started with the agent template: - -```sh -$ git clone https://github.com/slack-samples/bolt-python-assistant-template ai-app -$ cd ai-app -``` - -Using this method, be sure to set the app and bot tokens as we did in the [Running the app](#running-the-app) section above. - - - - -Once the project is created, update the `.env.sample` file by setting the `OPENAI_API_KEY` with the value of your key and removing the `.sample` from the file name. - -In the `ai` folder of this app, you'll find default instructions for the LLM and an OpenAI client setup. - -The `listeners` include utilities intended for messaging with an LLM. Those are outlined in detail in the guide to [Using AI in apps](/tools/bolt-python/concepts/ai-apps) and [Sending messages](/tools/bolt-python/concepts/message-sending). - ## Next steps {#next-steps} -Congrats once more on getting up and running with this quick start. - -:::info[Dive deeper] - -Follow along with the steps that went into making this app on the [building an app](/tools/bolt-python/building-an-app) guide for an educational overview. - -::: - You can now continue customizing your app with various features to make it right for whatever job's at hand. Here are some ideas about what to explore next: -- Explore the different events your bot can listen to with the [`app.event()`](/tools/bolt-python/concepts/event-listening) method. See the full events reference [here](/reference/events). -- Bolt allows you to call [Web API](/tools/bolt-python/concepts/web-api) methods with the client attached to your app. There are [over 200 methods](/reference/methods) available. -- Learn more about the different [token types](/authentication/tokens) and [authentication setups](/tools/bolt-python/concepts/authenticating-oauth). Your app might need different tokens depending on the actions you want to perform or for installations to multiple workspaces. -- Receive events using HTTP for various deployment methods, such as deploying to Heroku or AWS Lambda. -- Read on [app design](/surfaces/app-design) and compose fancy messages with blocks using [Block Kit Builder](https://app.slack.com/block-kit-builder) to prototype messages. +- Follow along with the steps that went into making this app on the [creating an app](/tools/bolt-python/creating-an-app) guide for an educational overview. +- Check out the [Agent quickstart](/ai/agent-quickstart) to get up and running with an agent. +- Browse our [curated catalog of samples](/samples) for more apps to use as a starting point for development. \ No newline at end of file diff --git a/docs/english/tutorial/ai-chatbot/ai-chatbot.md b/docs/english/tutorial/ai-chatbot/ai-chatbot.md index 72005f817..2fcc16e9a 100644 --- a/docs/english/tutorial/ai-chatbot/ai-chatbot.md +++ b/docs/english/tutorial/ai-chatbot/ai-chatbot.md @@ -1,64 +1,72 @@ # AI Chatbot -In this tutorial, you'll learn how to bring the power of AI into your Slack workspace using a chatbot called Bolty that uses Anthropic or OpenAI. Here's what we'll do with this sample app: - -1. Create your app from an app manifest and clone a starter template -2. Set up and run your local project -3. Create a workflow using Workflow Builder to summarize messages in conversations -4. Select your preferred API and model to customize Bolty's responses -5. Interact with Bolty via direct message, the `/ask-bolty` slash command, or by mentioning the app in conversations +In this tutorial, you'll learn how to bring the power of AI into your Slack workspace using a chatbot called Bolty that uses Anthropic or OpenAI. + +With Bolty, users can: + +- send direct messages to Bolty and get AI-powered responses in response, +- use the `/ask-bolty` slash command to ask Bolty questions, and +- receive channel summaries when joining new channels. + +Intrigued? First, grab your tools by following the three steps below. + +import QuickstartGuide from '@site/src/components/QuickstartGuide'; + + + +
      ## Prerequisites {#prereqs} -Before getting started, you will need the following: +You will also need the following: -- a development workspace where you have permissions to install apps. If you don’t have a workspace, go ahead and set that up now — you can [go here](https://slack.com/get-started#create) to create one, or you can join the [Developer Program](https://api.slack.com/developer-program) and provision a sandbox with access to all Slack features for free. +- a development workspace where you have permissions to install apps. If you don’t have a workspace you can join the [Developer Program](https://api.slack.com/developer-program) and provision a sandbox with access to all Slack features for free. - a development environment with [Python 3.7](https://www.python.org/downloads/) or later. - an Anthropic or OpenAI account with sufficient credits, and in which you have generated a secret key. -**Skip to the code** -If you'd rather skip the tutorial and just head straight to the code, you can use our [Bolt for Python AI Chatbot sample](https://github.com/slack-samples/bolt-python-ai-chatbot) as a template. - -## Creating your app {#create-app} - -1. Navigate to the [app creation page](https://api.slack.com/apps/new) and select **From a manifest**. -2. Select the workspace you want to install the application in. -3. Copy the contents of the [`manifest.json`](https://github.com/slack-samples/bolt-python-ai-chatbot/blob/main/manifest.json) file into the text box that says **Paste your manifest code here** (within the **JSON** tab) and click **Next**. -4. Review the configuration and click **Create**. -5. You're now in your app configuration's **Basic Information** page. Navigate to the **Install App** link in the left nav and click **Install to Workspace**, then **Allow** on the screen that follows. - ### Obtaining and storing your environment variables {#environment-variables} Before you'll be able to successfully run the app, you'll need to first obtain and set some environment variables. -#### Slack tokens {#slack-tokens} - -From your app's page on [app settings](https://api.slack.com/apps) collect an app and bot token: - -1. On the **Install App** page, copy your **Bot User OAuth Token**. You will store this in your environment as `SLACK_BOT_TOKEN` (we'll get to that next). -2. Navigate to **Basic Information** and in the **App-Level Tokens** section , click **Generate Token and Scopes**. Add the [`connections:write`](/reference/scopes/connections.write) scope, name the token, and click **Generate**. (For more details, refer to [understanding OAuth scopes for bots](/authentication/tokens#bot)). Copy this token. You will store this in your environment as `SLACK_APP_TOKEN`. - -To store your tokens and environment variables, run the following commands in the terminal. Replace the placeholder values with your bot and app tokens collected above: - -**For macOS** - -```bash -export SLACK_BOT_TOKEN= -export SLACK_APP_TOKEN= -``` - -**For Windows** - -```pwsh -set SLACK_BOT_TOKEN= -set SLACK_APP_TOKEN= -``` - #### Provider tokens {#provider-tokens} Models from different AI providers are available if the corresponding environment variable is added as shown in the sections below. -##### Anthropic {#anthropic} + + To interact with Anthropic models, navigate to your Anthropic account dashboard to [create an API key](https://console.anthropic.com/settings/keys), then export the key as follows: @@ -66,7 +74,8 @@ To interact with Anthropic models, navigate to your Anthropic account dashboard export ANTHROPIC_API_KEY= ``` -##### Google Cloud Vertex AI {#google-cloud-vertex-ai} + + To use Google Cloud Vertex AI, [follow this quick start](https://cloud.google.com/vertex-ai/generative-ai/docs/start/quickstarts/quickstart-multimodal#expandable-1) to create a project for sending requests to the Gemini API, then gather [Application Default Credentials](https://cloud.google.com/docs/authentication/provide-credentials-adc) with the strategy to match your development environment. @@ -79,7 +88,8 @@ export VERTEX_AI_LOCATION= The project location can be located under the **Region** on the [Vertex AI](https://console.cloud.google.com/vertex-ai) dashboard, as well as more details about available Gemini models. -##### OpenAI {#openai} + + Unlock the OpenAI models from your OpenAI account dashboard by clicking [create a new secret key](https://platform.openai.com/api-keys), then export the key like so: @@ -87,49 +97,46 @@ Unlock the OpenAI models from your OpenAI account dashboard by clicking [create export OPENAI_API_KEY= ``` -## Setting up and running your local project {#configure-project} - -Clone the starter template onto your machine by running the following command: - -```bash -git clone https://github.com/slack-samples/bolt-python-ai-chatbot.git -``` + + -Change into the new project directory: +## Setting up and running your local project {#configure-project} -```bash -cd bolt-python-ai-chatbot -``` Start your Python virtual environment: -**For macOS** + + ```bash python3 -m venv .venv source .venv/bin/activate ``` -**For Windows** + + ```bash py -m venv .venv .venv\Scripts\activate ``` + + + Install the required dependencies: ```bash pip install -r requirements.txt ``` -Start your local server: +Run your app locally: ```bash -python app.py +slack run ``` -If your app is up and running, you'll see a message that says "⚡️ Bolt app is running!" +If your app is indeed up and running, you'll see a message that says "⚡️ Bolt app is running!" ## Choosing your provider {#provider} @@ -235,5 +242,4 @@ You can also navigate to **Bolty** in your **Apps** list and select the **Messag Congratulations! You've successfully integrated the power of AI into your workspace. Check out these links to take the next steps in your Bolt for Python journey. - To learn more about Bolt for Python, refer to the [Getting started](/tools/bolt-python/getting-started) documentation. -- For more details about creating workflow steps using the Bolt SDK, refer to the [workflow steps for Bolt](/workflows/workflow-steps) guide. -- To use the Bolt for Python SDK to develop on the automations platform, refer to the [Create a workflow step for Workflow Builder: Bolt for Python](/tools/bolt-python/tutorial/custom-steps-workflow-builder-new) tutorial. +- For more details about creating workflow steps using the Bolt SDK, refer to the [workflow steps for Bolt](/workflows/workflow-steps) guide. \ No newline at end of file diff --git a/docs/japanese/concepts/assistant.md b/docs/japanese/concepts/assistant.md deleted file mode 100644 index 664108607..000000000 --- a/docs/japanese/concepts/assistant.md +++ /dev/null @@ -1,227 +0,0 @@ -# エージェント・アシスタント - -このページは、Bolt を使ってエージェント・アシスタントを実装するための方法を紹介します。この機能に関する一般的な情報については、[こちらのドキュメントページ(英語)](/ai/)を参照してください。 - -この機能を実装するためには、まず[アプリの設定画面](https://api.slack.com/apps)で **Agents & Assistants** 機能を有効にし、**OAuth & Permissions** のページで [`assistant:write`](/reference/scopes/assistant.write)、[chat:write](/reference/scopes/chat.write)、[`im:history`](/reference/scopes/im.history) を**ボットの**スコープに追加し、**Event Subscriptions** のページで [`assistant_thread_started`](/reference/events/assistant_thread_started)、[`assistant_thread_context_changed`](/reference/events/assistant_thread_context_changed)、[`message.im`](/reference/events/message.im) イベントを有効にしてください。 - -また、この機能は Slack の有料プランでのみ利用可能です。もし開発用の有料プランのワークスペースをお持ちでない場合は、[Developer Program](https://api.slack.com/developer-program) に参加し、全ての有料プラン向け機能を利用可能なサンドボックス環境をつくることができます。 - -ユーザーとのアシスタントスレッド内でのやりとりを処理するには、`assistant_thread_started`、`assistant_thread_context_changed`、`message` イベントの `app.event(...)` リスナーを使うことも可能ですが、Bolt はよりシンプルなアプローチを提供しています。`Assistant` インスタンスを作り、それに必要なイベントリスナーを追加し、最後にこのアシスタント設定を `App` インスタンスに渡すだけでよいのです。 - -```python -assistant = Assistant() - -# ユーザーがアシスタントスレッドを開いたときに呼び出されます -@assistant.thread_started -def start_assistant_thread(say: Say, set_suggested_prompts: SetSuggestedPrompts): - # ユーザーに対して最初の返信を送信します - say(":wave: Hi, how can I help you today?") - - # プロンプト例を送るのは必須ではありません - set_suggested_prompts( - prompts=[ - # もしプロンプトが長い場合は {"title": "表示する短いラベル", "message": "完全なプロンプト"} を使うことができます - "What does SLACK stand for?", - "When Slack was released?", - ], - ) - -# ユーザーがスレッド内で返信したときに呼び出されます -@assistant.user_message -def respond_in_assistant_thread( - payload: dict, - logger: logging.Logger, - context: BoltContext, - set_status: SetStatus, - say: Say, - client: WebClient, -): - try: - # ユーザーにこのbotがリクエストを受信して作業中であることを伝えます - set_status("is typing...") - - # 会話の履歴を取得します - replies_in_thread = client.conversations_replies( - channel=context.channel_id, - ts=context.thread_ts, - oldest=context.thread_ts, - limit=10, - ) - messages_in_thread: List[Dict[str, str]] = [] - for message in replies_in_thread["messages"]: - role = "user" if message.get("bot_id") is None else "assistant" - messages_in_thread.append({"role": role, "content": message["text"]}) - - # プロンプトと会話の履歴を LLM に渡します(この call_llm はあなた自身のコードです) - returned_message = call_llm(messages_in_thread) - - # 結果をアシスタントスレッドに送信します - say(text=returned_message) - - except Exception as e: - logger.exception(f"Failed to respond to an inquiry: {e}") - # エラーになった場合は必ずメッセージを送信するようにしてください - # そうしなかった場合、'is typing...' の表示のままになってしまい、ユーザーは会話を続けることができなくなります - say(f":warning: Sorry, something went wrong during processing your request (error: {e})") - -# このミドルウェアを Bolt アプリに追加します -app.use(assistant) -``` - -リスナーに指定可能な引数の一覧は[モジュールドキュメント](https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html)を参考にしてください。 - -ユーザーがチャンネルの横でアシスタントスレッドを開いた場合、そのチャンネルの情報は、そのスレッドの `AssistantThreadContext` データとして保持され、 `get_thread_context` ユーティリティを使ってアクセスすることができます。Bolt がこのユーティリティを提供している理由は、後続のユーザーメッセージ投稿のイベントペイロードに最新のスレッドのコンテキスト情報は含まれないためです。そのため、アプリはコンテキスト情報が変更されたタイミングでそれを何らかの方法で保存し、後続のメッセージイベントのリスナーコードから参照できるようにする必要があります。 - -そのユーザーがチャンネルを切り替えた場合、`assistant_thread_context_changed` イベントがあなたのアプリに送信されます。(上記のコード例のように)組み込みの `Assistant` ミドルウェアをカスタム設定なしで利用している場合、この更新されたチャンネル情報は、自動的にこのアシスタントボットからの最初の返信のメッセージメタデータとして保存されます。これは、組み込みの仕組みを使う場合は、このコンテキスト情報を自前で用意したデータストアに保存する必要はないということです。この組み込みの仕組みの唯一の短所は、追加の Slack API 呼び出しによる処理時間のオーバーヘッドです。具体的には `get_thread_context` を実行したときに、この保存されたメッセージメタデータにアクセスするために `conversations.history` API が呼び出されます。 - -このデータを別の場所に保存したい場合、自前の `AssistantThreadContextStore` 実装を `Assistant` のコンストラクターに渡すことができます。リファレンス実装として、`FileAssistantThreadContextStore` というローカルファイルシステムを使って実装を提供しています: - -```python -# これはあくまで例であり、自前のものを渡すことができます -from slack_bolt import FileAssistantThreadContextStore -assistant = Assistant(thread_context_store=FileAssistantThreadContextStore()) -``` - -このリファレンス実装はローカルファイルに依存しており、本番環境での利用は推奨しません。本番アプリでは `AssistantThreadContextStore` を継承した自前のクラスを使うようにしてください。 - -最後に、動作する完全なサンプルコード例を確認したい場合は、私たちが GitHub 上で提供している[サンプルアプリのリポジトリ](https://github.com/slack-samples/bolt-python-assistant-template)をチェックしてみてください。 - -## アシスタントスレッドでの Block Kit インタラクション - -より高度なユースケースでは、上のようなプロンプト例の提案ではなく Block Kit のボタンなどを使いたいという場合があるかもしれません。そして、後続の処理のために[構造化されたメッセージメタデータ](/messaging/message-metadata/)を含むメッセージを送信したいという場合もあるでしょう。 - -例えば、アプリが最初の返信で「参照しているチャンネルを要約」のようなボタンを表示し、ユーザーがそれをクリックして、より詳細な情報(例:要約するメッセージ数・日数、要約の目的など)を送信、アプリがそれを構造化されたメータデータに整理した上でリクエスト内容をボットのメッセージとして送信するようなシナリオです。 - -デフォルトでは、アプリはそのアプリ自身から送信したボットメッセージに応答することはできません(Bolt にはあらかじめ無限ループを防止する制御が入っているため)。`ignoring_self_assistant_message_events_enabled=False` を `App` のコンストラクターに渡し、`bot_message` リスナーを `Assistant` ミドルウェアに追加すると、上記の例のようなリクエストを伝えるボットメッセージを使って処理を継続することができるようになります。 - -```python -app = App( - token=os.environ["SLACK_BOT_TOKEN"], - # bot message を受け取るには必ずこれを指定してください - ignoring_self_assistant_message_events_enabled=False, -) - -assistant = Assistant() - -# リスナーに指定可能な引数の一覧は https://docs.slack.dev/tools/bolt-python/reference/kwargs_injection/args.html を参照してください - -@assistant.thread_started -def start_assistant_thread(say: Say): - say( - text=":wave: Hi, how can I help you today?", - blocks=[ - { - "type": "section", - "text": {"type": "mrkdwn", "text": ":wave: Hi, how can I help you today?"}, - }, - { - "type": "actions", - "elements": [ - # 複数のボタンを配置することが可能です - { - "type": "button", - "action_id": "assistant-generate-random-numbers", - "text": {"type": "plain_text", "text": "Generate random numbers"}, - "value": "clicked", - }, - ], - }, - ], - ) - -# 上のボタンがクリックされたときに実行されます -@app.action("assistant-generate-random-numbers") -def configure_random_number_generation(ack: Ack, client: WebClient, body: dict): - ack() - client.views_open( - trigger_id=body["trigger_id"], - view={ - "type": "modal", - "callback_id": "configure_assistant_summarize_channel", - "title": {"type": "plain_text", "text": "My Assistant"}, - "submit": {"type": "plain_text", "text": "Submit"}, - "close": {"type": "plain_text", "text": "Cancel"}, - # アシスタントスレッドの情報を app.view リスナーに引き継ぎます - "private_metadata": json.dumps( - { - "channel_id": body["channel"]["id"], - "thread_ts": body["message"]["thread_ts"], - } - ), - "blocks": [ - { - "type": "input", - "block_id": "num", - "label": {"type": "plain_text", "text": "# of outputs"}, - # 自然言語のテキストではなく、あらかじめ決められた形式の入力を受け取ることができます - "element": { - "type": "static_select", - "action_id": "input", - "placeholder": {"type": "plain_text", "text": "How many numbers do you need?"}, - "options": [ - {"text": {"type": "plain_text", "text": "5"}, "value": "5"}, - {"text": {"type": "plain_text", "text": "10"}, "value": "10"}, - {"text": {"type": "plain_text", "text": "20"}, "value": "20"}, - ], - "initial_option": {"text": {"type": "plain_text", "text": "5"}, "value": "5"}, - }, - } - ], - }, - ) - -# 上のモーダルが送信されたときに実行されます -@app.view("configure_assistant_summarize_channel") -def receive_random_number_generation_details(ack: Ack, client: WebClient, payload: dict): - ack() - num = payload["state"]["values"]["num"]["input"]["selected_option"]["value"] - thread = json.loads(payload["private_metadata"]) - - # 構造化された入力情報とともにボットのメッセージを送信します - # 以下の assistant.bot_message リスナーが処理を継続します - # このリスナー内で処理したい場合はそれでも構いません! - # bot_message リスナーが必要ない場合は ignoring_self_assistant_message_events_enabled=False を設定する必要はありません - client.chat_postMessage( - channel=thread["channel_id"], - thread_ts=thread["thread_ts"], - text=f"OK, you need {num} numbers. I will generate it shortly!", - metadata={ - "event_type": "assistant-generate-random-numbers", - "event_payload": {"num": int(num)}, - }, - ) - -# このアプリのボットユーザーがメッセージを送信したときに実行されます -@assistant.bot_message -def respond_to_bot_messages(logger: logging.Logger, set_status: SetStatus, say: Say, payload: dict): - try: - if payload.get("metadata", {}).get("event_type") == "assistant-generate-random-numbers": - # 上の random-number-generation リクエストを処理します - set_status("is generating an array of random numbers...") - time.sleep(1) - nums: Set[str] = set() - num = payload["metadata"]["event_payload"]["num"] - while len(nums) < num: - nums.add(str(random.randint(1, 100))) - say(f"Here you are: {', '.join(nums)}") - else: - # それ以外のパターンでは何もしません - # さらに他のパターンを追加する場合、メッセージ送信の無限ループを起こさないよう注意して実装してください - pass - - except Exception as e: - logger.exception(f"Failed to respond to an inquiry: {e}") - -# ユーザーが返信したときに実行されます -@assistant.user_message -def respond_to_user_messages(logger: logging.Logger, set_status: SetStatus, say: Say): - try: - set_status("is typing...") - say("Please use the buttons in the first reply instead :bow:") - except Exception as e: - logger.exception(f"Failed to respond to an inquiry: {e}") - say(f":warning: Sorry, something went wrong during processing your request (error: {e})") - -# このミドルウェアを Bolt アプリに追加します -app.use(assistant) -``` \ No newline at end of file From 2266ac7d9ea8c36c2b17266eb6e1dc45578372aa Mon Sep 17 00:00:00 2001 From: Sascha Buehrle <47737812+saschabuehrle@users.noreply.github.com> Date: Mon, 13 Apr 2026 15:53:11 +0200 Subject: [PATCH 7/7] fix: handle malformed user/view payloads in extract_team_id (#1481) --- slack_bolt/request/internals.py | 4 ++-- tests/slack_bolt/request/test_internals.py | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/slack_bolt/request/internals.py b/slack_bolt/request/internals.py index 15d1e7367..e0863a713 100644 --- a/slack_bolt/request/internals.py +++ b/slack_bolt/request/internals.py @@ -112,9 +112,9 @@ def extract_team_id(payload: Dict[str, Any]) -> Optional[str]: if isinstance(payload.get("event"), dict): return extract_team_id(payload["event"]) if isinstance(payload.get("user"), dict): - return payload["user"]["team_id"] + return payload["user"].get("team_id") if isinstance(payload.get("view"), dict): - return payload["view"]["team_id"] + return payload["view"].get("team_id") return None diff --git a/tests/slack_bolt/request/test_internals.py b/tests/slack_bolt/request/test_internals.py index 8cccf0431..31ac35bdd 100644 --- a/tests/slack_bolt/request/test_internals.py +++ b/tests/slack_bolt/request/test_internals.py @@ -1253,8 +1253,10 @@ def test_extraction_functions_invalid_dict_keys(self): invalid_payloads = { "event": {"event": "some_event_type"}, "user": {"user": "U12345"}, + "user_missing_team_id": {"user": {"id": "U12345"}}, "team": {"team": "T12345"}, "view": {"view": "V12345"}, + "view_missing_team_id": {"view": {"id": "V12345"}}, "message": {"message": "some text"}, "item": {"item": "item_id"}, "function_data": {"function_data": "fd_123"},