diff --git a/.claude/skills/managing-dependencies/SKILL.md b/.claude/skills/managing-dependencies/SKILL.md
new file mode 100644
index 000000000..335ac7d0a
--- /dev/null
+++ b/.claude/skills/managing-dependencies/SKILL.md
@@ -0,0 +1,81 @@
+---
+name: managing-dependencies
+description: >-
+ Use when adding, bumping, pinning, or reviewing a dependency in requirements.txt or requirements/*.txt, including taking or fixing a Dependabot PR. Also use when pip install fails on some Python versions in CI but not others ("Could not find a version that satisfies the requirement", "No matching distribution found", "Requires-Python", "ResolutionImpossible"), including PyPy-only failures, and when dropping support for an old Python version.
+---
+
+# Managing dependencies
+
+This repo supports a range of Python versions, and one set of requirements files has to install on all of them. Dependabot proposes the newest release, so its bumps often raise a lower bound past what the oldest Pythons can install, and CI fails at the install step on those jobs only. The fix is to split the requirement with PEP 508 `python_version` markers so each Python gets the newest release it can install. Dropping an old Python to turn CI green is not the fix.
+
+## Where the facts live
+
+Read these instead of trusting memory; they change often.
+
+- **Supported Pythons:** `requires-python` and the `Programming Language :: Python :: 3.X` classifiers in `pyproject.toml`, and the CI matrix.
+- **Who installs a file, on which Python:** `grep -rn requirements .github/workflows scripts requirements pyproject.toml`. This also catches `-r` includes. For a hit in a script, find the CI job that runs it and read its `python-version`.
+- **Whether a file ships to users:** a file that `pyproject.toml` reads into package metadata (`dependencies` or `optional-dependencies` under `[tool.setuptools.dynamic]`) ends up in the published wheel.
+
+## Workflow
+
+- [ ] 1. Find which Pythons install the file. A file installed only on the newest Python takes the bump as-is.
+- [ ] 2. Find the newest release each affected Python can install (see "Finding the ceiling").
+- [ ] 3. If every Python the line covers can install the new lower bound, take the bump as one line. Done.
+- [ ] 4. Otherwise split the line (see "Splitting a line").
+- [ ] 5. Re-read the section: no Python matches two lines, and the newest line is open-ended.
+
+Change only the section you are fixing; don't reformat other sections in the same change.
+
+## File layout
+
+Each file starts with a `# pip install -r
async def run_async_bolt_app(app: AsyncApp, req: SocketModeRequest):
- bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload)
+ bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
bolt_resp: BoltResponse = await app.async_dispatch(bolt_req)
return bolt_resp
diff --git a/docs/reference/adapter/socket_mode/internals.html b/docs/reference/adapter/socket_mode/internals.html
index 55d96b054..ba7d2f226 100644
--- a/docs/reference/adapter/socket_mode/internals.html
+++ b/docs/reference/adapter/socket_mode/internals.html
@@ -45,6 +45,25 @@ slack_bolt.adapter.socket_mode.internals
+def build_headers(req: slack_sdk.socket_mode.request.SocketModeRequest) ‑> Dict[str, str | Sequence[str]] | None
+def build_headers(req: SocketModeRequest) -> Optional[Dict[str, Union[str, Sequence[str]]]]:
+ # Mirror the HTTP mode retry headers so middleware/listeners can detect Events API retries
+ headers: Dict[str, Union[str, Sequence[str]]] = {}
+ if req.retry_attempt is not None:
+ headers["x-slack-retry-num"] = str(req.retry_attempt)
+ if req.retry_reason is not None:
+ headers["x-slack-retry-reason"] = req.retry_reason
+ return headers or None
+
def run_bolt_app(app: App,
req: slack_sdk.socket_mode.request.SocketModeRequest)
def run_bolt_app(app: App, req: SocketModeRequest):
- bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload)
+ bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
bolt_resp: BoltResponse = app.dispatch(bolt_req)
return bolt_resp
@@ -111,6 +130,7 @@ Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers. This can be used for production deployments.
diff --git a/docs/reference/adapter/wsgi/http_request.html b/docs/reference/adapter/wsgi/http_request.html index fa845dd93..72c5f28be 100644 --- a/docs/reference/adapter/wsgi/http_request.html +++ b/docs/reference/adapter/wsgi/http_request.html @@ -48,7 +48,7 @@
class WsgiHttpRequest
-(environ: Dict[str, Any])
+(environ: WSGIEnvironment)
This Class uses the PEP 3333 standard to extract request information @@ -108,7 +108,7 @@
def get_body(self) -> str:
if "wsgi.input" not in self.environ:
return ""
- content_length = int(self.environ.get("CONTENT_LENGTH", 0))
+ content_length = int(self.environ.get("CONTENT_LENGTH") or 0)
return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
diff --git a/docs/reference/adapter/wsgi/http_response.html b/docs/reference/adapter/wsgi/http_response.html
index da7dc33f0..726332c77 100644
--- a/docs/reference/adapter/wsgi/http_response.html
+++ b/docs/reference/adapter/wsgi/http_response.html
@@ -48,7 +48,7 @@
class WsgiHttpResponse
-(status: int, headers: Dict[str, Sequence[str]] = {}, body: str = '')
+(status: int, headers: Dict[str, Sequence[str]] | None = None, body: str = '')
def get_headers(self) -> List[Tuple[str, str]]:
headers: List[Tuple[str, str]] = []
- for key, value in self._headers.items():
+ for key, values in self._headers.items():
if key.lower() == "content-length":
continue
- headers.append((key, value[0]))
+ for v in values:
+ headers.append((key, v))
headers.append(("content-length", str(len(self._body))))
return headers
diff --git a/docs/reference/adapter/wsgi/index.html b/docs/reference/adapter/wsgi/index.html
index c3cfafea1..186d1adf6 100644
--- a/docs/reference/adapter/wsgi/index.html
+++ b/docs/reference/adapter/wsgi/index.html
@@ -136,17 +136,20 @@ Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers. This can be used for production deployments.
diff --git a/docs/reference/app/app.html b/docs/reference/app/app.html index bf0d5ee00..737597548 100644 --- a/docs/reference/app/app.html +++ b/docs/reference/app/app.html @@ -118,7 +118,7 @@Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.
+Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.
If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.
Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.
+Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.
If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.
class AsyncSetSuggestedPrompts
-(client: slack_sdk.web.async_client.AsyncWebClient,
channel_id: str,
thread_ts: str)
+(client: slack_sdk.web.async_client.AsyncWebClient,
channel_id: str,
thread_ts: str | None = None)
class AsyncSetSuggestedPrompts:
client: AsyncWebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: AsyncWebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -5426,6 +5441,7 @@ Class variables
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> AsyncSlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -5436,7 +5452,7 @@ Class variables
return await self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
@@ -5452,7 +5468,7 @@ The type of the None singleton.
var thread_ts : strvar thread_ts : str | NoneThe type of the None singleton.
prop set_status : SetStatus@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)
-prop set_suggested_prompts : SetSuggestedPrompts@property
-def set_suggested_prompts(self) -> SetSuggestedPrompts:
- return SetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
-prop set_title : SetTitle
-def is_valid(self) ‑> bool
-def is_valid(self) -> bool:
- return self.channel_id is not None and self.thread_ts is not None
-channel_id
clientget_thread_contextis_validpayloadsave_thread_contextsayset_statusset_suggested_promptsset_titlethread_context_storethread_tsprop set_status : AsyncSetStatus@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)
-prop set_suggested_prompts : AsyncSetSuggestedPrompts@property
-def set_suggested_prompts(self) -> AsyncSetSuggestedPrompts:
- return AsyncSetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
-prop set_title : AsyncSetTitle
-def is_valid(self) ‑> bool
-def is_valid(self) -> bool:
- return self.channel_id is not None and self.thread_ts is not None
-channel_id
clientget_thread_contextis_validpayloadsave_thread_contextsayset_statusset_suggested_promptsset_titlethread_context_storethread_ts
class FileAssistantThreadContextStore
-(base_dir: str = '/Users/eden.zimbelman/.bolt-app-assistant-thread-contexts')
+(base_dir: str = '/Users/wbergamin/.bolt-app-assistant-thread-contexts')
class AsyncSetSuggestedPrompts
-(client: slack_sdk.web.async_client.AsyncWebClient,
channel_id: str,
thread_ts: str)
+(client: slack_sdk.web.async_client.AsyncWebClient,
channel_id: str,
thread_ts: str | None = None)
class AsyncSetSuggestedPrompts:
client: AsyncWebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: AsyncWebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -74,6 +74,7 @@ Classes
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> AsyncSlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -84,7 +85,7 @@ Classes
return await self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
@@ -100,7 +101,7 @@ The type of the None singleton.
var thread_ts : strvar thread_ts : str | NoneThe type of the None singleton.
class SetSuggestedPrompts
-(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str)
+(client: slack_sdk.web.client.WebClient,
channel_id: str,
thread_ts: str | None = None)
class SetSuggestedPrompts:
client: WebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: WebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -85,6 +85,7 @@ Classes
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> SlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -95,7 +96,7 @@ Classes
return self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
@@ -111,7 +112,7 @@ The type of the None singleton.
var thread_ts : strvar thread_ts : str | NoneThe type of the None singleton.
class SetSuggestedPrompts
-(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str)
+(client: slack_sdk.web.client.WebClient,
channel_id: str,
thread_ts: str | None = None)
class SetSuggestedPrompts:
client: WebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: WebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -74,6 +74,7 @@ Classes
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> SlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -84,7 +85,7 @@ Classes
return self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
@@ -100,7 +101,7 @@ The type of the None singleton.
var thread_ts : strvar thread_ts : str | NoneThe type of the None singleton.
class BoltUnhandledRequestError
-(*,
request: ForwardRef('BoltRequest') | ForwardRef('AsyncBoltRequest'),
current_response: ForwardRef('BoltResponse') | None,
last_global_middleware_name: str | None = None)
+(*,
request: BoltRequest | AsyncBoltRequest,
current_response: BoltResponse | None,
last_global_middleware_name: str | None = None)
slack_boltA Python framework to build Slack apps in a flash with the latest platform features.Read the getting started guide and look at our code examples to learn how to build apps using Bolt.
+A Python framework to build Slack apps in a flash with the latest platform features.Read the getting started guide and look at our code examples to learn how to build apps using Bolt.
Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.
+Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.
If you would like to build an OAuth app for enabling the app to run with multiple workspaces, refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.
class FileAssistantThreadContextStore
-(base_dir: str = '/Users/eden.zimbelman/.bolt-app-assistant-thread-contexts')
+(base_dir: str = '/Users/wbergamin/.bolt-app-assistant-thread-contexts')
class SetSuggestedPrompts
-(client: slack_sdk.web.client.WebClient, channel_id: str, thread_ts: str)
+(client: slack_sdk.web.client.WebClient,
channel_id: str,
thread_ts: str | None = None)
class SetSuggestedPrompts:
client: WebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: WebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -6050,6 +6065,7 @@ Class variables
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> SlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -6060,7 +6076,7 @@ Class variables
return self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
@@ -6076,7 +6092,7 @@ The type of the None singleton.
var thread_ts : strvar thread_ts : str | NoneThe type of the None singleton.
-def warning_unhandled_by_global_middleware(name: str,
req: BoltRequest | ForwardRef('AsyncBoltRequest')) ‑> str
+def warning_unhandled_by_global_middleware(name: str,
req: BoltRequest | AsyncBoltRequest) ‑> str
-def warning_unhandled_request(req: BoltRequest | ForwardRef('AsyncBoltRequest')) ‑> str
+def warning_unhandled_request(req: BoltRequest | AsyncBoltRequest) ‑> str
A middleware can process request data before other middleware and listener functions.
A middleware can process request data before other middleware and listener functions.
A middleware can process request data before other middleware and listener functions.
A middleware can process request data before other middleware and listener functions.
A middleware can process request data before other middleware and listener functions.
prop verifier : slack_sdk.signature.SignatureVerifier@property
+def verifier(self) -> SignatureVerifier:
+ # Defer initialization to avoid errors during start up
+ if self._verifier is None:
+ self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
+ return self._verifier
+Middleware:
@@ -1139,6 +1181,9 @@ RequestVerificationverifierSingleTeamAuthorizationprop verifier : slack_sdk.signature.SignatureVerifier@property
+def verifier(self) -> SignatureVerifier:
+ # Defer initialization to avoid errors during start up
+ if self._verifier is None:
+ self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
+ return self._verifier
+Middleware:
@@ -169,6 +195,9 @@ prop verifier : slack_sdk.signature.SignatureVerifier@property
+def verifier(self) -> SignatureVerifier:
+ # Defer initialization to avoid errors during start up
+ if self._verifier is None:
+ self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
+ return self._verifier
+Middleware:
@@ -152,6 +178,9 @@
class AsyncOAuthSettings
-(*,
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)>)
+(*,
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)>)
class OAuthSettings
-(*,
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)>)
+(*,
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)>)
+def is_any_im_message_event(body: Dict[str, Any]) ‑> bool
+def is_any_im_message_event(body: Dict[str, Any]) -> bool:
+ if is_message_event(body):
+ # Any message event with no subtype or any subtype (message_changed, message_deleted, etc.)
+ return body["event"].get("channel_type") == "im"
+ return False
+
+def is_app_home_opened_event(body: Dict[str, Any], tab: str | None = None) ‑> bool
+def is_app_home_opened_event(body: Dict[str, Any], tab: Optional[str] = None) -> bool:
+ if is_event(body) and body["event"]["type"] == "app_home_opened":
+ if tab is not None:
+ return body["event"].get("tab") == tab
+ return True
+ return False
+
def is_assistant_event(body: Dict[str, Any]) ‑> bool
def is_bot_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
- if is_event(body):
+ if is_any_im_message_event(body):
return (
- is_message_event_in_assistant_thread(body)
- and body["event"].get("subtype") is None
+ body["event"].get("subtype") is None
and body["event"].get("thread_ts") is not None
and body["event"].get("bot_id") is not None
)
@@ -248,17 +280,32 @@ Functions
-def is_message_event_in_assistant_thread(body: Dict[str, Any]) ‑> bool
+
+def is_im_message_event(body: Dict[str, Any]) ‑> bool
+
+-
+
+
+Expand source code
+
+def is_im_message_event(body: Dict[str, Any]) -> bool:
+ if is_any_im_message_event(body):
+ return body["event"].get("subtype") in (None, "file_share")
+ return False
+
+
+
+
+def is_message_event(body: Dict[str, Any]) ‑> bool
-
Expand source code
-def is_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
+def is_message_event(body: Dict[str, Any]) -> bool:
if is_event(body):
- return body["event"]["type"] == "message" and body["event"].get("channel_type") == "im"
+ return body["event"]["type"] == "message"
return False
@@ -299,14 +346,10 @@ Functions
def is_other_message_sub_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
# message_changed, message_deleted etc.
- if is_event(body):
- return (
- is_message_event_in_assistant_thread(body)
- and not is_user_message_event_in_assistant_thread(body)
- and (
- _is_other_message_sub_event(body["event"].get("message"))
- or _is_other_message_sub_event(body["event"].get("previous_message"))
- )
+ if is_any_im_message_event(body):
+ return not is_user_message_event_in_assistant_thread(body) and (
+ _is_other_message_sub_event(body["event"].get("message"))
+ or _is_other_message_sub_event(body["event"].get("previous_message"))
)
return False
@@ -347,13 +390,8 @@ Functions
Expand source code
def is_user_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
- if is_event(body):
- return (
- is_message_event_in_assistant_thread(body)
- and body["event"].get("subtype") in (None, "file_share")
- and body["event"].get("thread_ts") is not None
- and body["event"].get("bot_id") is None
- )
+ if is_im_message_event(body):
+ return body["event"].get("thread_ts") is not None and body["event"].get("bot_id") is None
return False
@@ -491,7 +529,7 @@ Functions
Expand source code
def to_message(body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
- if is_event(body) and body["event"]["type"] == "message":
+ if is_message_event(body):
return to_event(body)
return None
@@ -582,6 +620,8 @@ Functions
Functions
is_action
+is_any_im_message_event
+is_app_home_opened_event
is_assistant_event
is_assistant_thread_context_changed_event
is_assistant_thread_started_event
@@ -595,7 +635,8 @@ Functions
is_event
is_function
is_global_shortcut
-is_message_event_in_assistant_thread
+is_im_message_event
+is_message_event
is_message_shortcut
is_options
is_other_message_sub_event_in_assistant_thread
diff --git a/examples/assistants/async_interaction_app.py b/examples/assistants/async_interaction_app.py
index b9e8de3bc..d2cb0e449 100644
--- a/examples/assistants/async_interaction_app.py
+++ b/examples/assistants/async_interaction_app.py
@@ -1,4 +1,4 @@
-# flake8: noqa F811
+# ruff: noqa: F811
import asyncio
import logging
import os
diff --git a/examples/aws_lambda/README.md b/examples/aws_lambda/README.md
index 49a8f7da2..2fc34b7cf 100644
--- a/examples/aws_lambda/README.md
+++ b/examples/aws_lambda/README.md
@@ -33,15 +33,15 @@ Instructions on how to set up and deploy each example are provided below.
- Optionally enter a description for the role, such as "Bolt Python basic
role"
3. Ensure you have created an app on api.slack.com/apps as per the
- [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide.
+ [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide.
Ensure you have installed it to a workspace.
4. Ensure you have exported your Slack Bot Token and Slack Signing Secret for your
apps as the environment variables `SLACK_BOT_TOKEN` and
`SLACK_SIGNING_SECRET`, respectively, as per the
- [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide.
+ [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide.
5. You may want to create a dedicated virtual environment for this example app, as
per the "Setting up your project" section of the
- [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide.
+ [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide.
6. Let's deploy the Lambda! Run `./deploy_lazy.sh`. By default it deploys to the
us-east-1 region in AWS - you can change this at the top of `lazy_aws_lambda_config.yaml` if you wish.
7. Load up AWS Lambda inside the AWS Console - make sure you are in the correct
@@ -150,7 +150,7 @@ Let’s create a user role that will use the custom policy we created as well as
3. "Create Role"
### Create Slack App and Load your Lambda to AWS
-Ensure you have created an app on [api.slack.com/apps](https://api.slack.com/apps) as per the [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide. You do not need to ensure you have installed it to a workspace, as the OAuth flow will provide your app the ability to be installed by anyone.
+Ensure you have created an app on [api.slack.com/apps](https://api.slack.com/apps) as per the [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide. You do not need to ensure you have installed it to a workspace, as the OAuth flow will provide your app the ability to be installed by anyone.
1. Remember those S3 buckets we made? You will need the names of these buckets again in the next step.
2. You need many environment variables exported! Specifically the following from api.slack.com/apps
diff --git a/examples/django/README.md b/examples/django/README.md
index ca0460fd1..cb29a822b 100644
--- a/examples/django/README.md
+++ b/examples/django/README.md
@@ -4,7 +4,7 @@ This example demonstrates how you can use Bolt for Python in your Django applica
### `simple_app` - Single-workspace App Example
-If you want to run a simple app like the one you've tried in the [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide, this is the right one for you. By default, this Django project runs this application. If you want to switch to OAuth flow supported one, modify `myslackapp/urls.py`.
+If you want to run a simple app like the one you've tried in the [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide, this is the right one for you. By default, this Django project runs this application. If you want to switch to OAuth flow supported one, modify `myslackapp/urls.py`.
To run this app, all you need to do are:
@@ -31,7 +31,7 @@ python manage.py migrate
python manage.py runserver 0.0.0.0:3000
```
-As you did at [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide, configure ngrok or something similar to serve a public endpoint. Lastly,
+As you did at [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide, configure ngrok or something similar to serve a public endpoint. Lastly,
* Go back to the Slack app configuration page
* Go to "Event Subscriptions"
@@ -73,7 +73,7 @@ python manage.py migrate
python manage.py runserver 0.0.0.0:3000
```
-As you did at [Building an App](https://docs.slack.dev/tools/bolt-python/building-an-app) guide, configure ngrok or something similar to serve a public endpoint. Lastly,
+As you did at [Building an App](https://docs.slack.dev/tools/bolt-python/creating-an-app) guide, configure ngrok or something similar to serve a public endpoint. Lastly,
* Go back to the Slack app configuration page
* Go to "Event Subscriptions"
diff --git a/examples/django/manage.py b/examples/django/manage.py
index cec2fe4e4..6e66426e5 100755
--- a/examples/django/manage.py
+++ b/examples/django/manage.py
@@ -1,5 +1,6 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
+
import os
import sys
diff --git a/examples/django/myslackapp/asgi.py b/examples/django/myslackapp/asgi.py
index 814c38df4..39a2a58ee 100644
--- a/examples/django/myslackapp/asgi.py
+++ b/examples/django/myslackapp/asgi.py
@@ -1,5 +1,4 @@
-"""
-ASGI config for myslackapp project.
+"""ASGI config for myslackapp project.
It exposes the ASGI callable as a module-level variable named ``application``.
diff --git a/examples/django/myslackapp/settings.py b/examples/django/myslackapp/settings.py
index a99c91188..4cde94ac9 100644
--- a/examples/django/myslackapp/settings.py
+++ b/examples/django/myslackapp/settings.py
@@ -1,5 +1,4 @@
-"""
-Django settings for myslackapp project.
+"""Django settings for myslackapp project.
Generated by 'django-admin startproject' using Django 3.2.3.
@@ -9,6 +8,7 @@
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
+
import os
from pathlib import Path
diff --git a/examples/django/myslackapp/urls.py b/examples/django/myslackapp/urls.py
index f3d5c7268..6e5db7b8f 100644
--- a/examples/django/myslackapp/urls.py
+++ b/examples/django/myslackapp/urls.py
@@ -1,7 +1,8 @@
-"""myslackapp URL Configuration
+"""myslackapp URL Configuration.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
+
Examples:
Function views
1. Add an import: from my_app import views
@@ -13,6 +14,7 @@
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
+
from django.contrib import admin # noqa: F401
from django.urls import path
diff --git a/examples/django/myslackapp/wsgi.py b/examples/django/myslackapp/wsgi.py
index 4443e81cb..717fcb796 100644
--- a/examples/django/myslackapp/wsgi.py
+++ b/examples/django/myslackapp/wsgi.py
@@ -1,5 +1,4 @@
-"""
-WSGI config for myslackapp project.
+"""WSGI config for myslackapp project.
It exposes the WSGI callable as a module-level variable named ``application``.
diff --git a/examples/django/oauth_app/migrations/0001_initial.py b/examples/django/oauth_app/migrations/0001_initial.py
index d5e3113c6..2d7b9cfed 100644
--- a/examples/django/oauth_app/migrations/0001_initial.py
+++ b/examples/django/oauth_app/migrations/0001_initial.py
@@ -4,7 +4,6 @@
class Migration(migrations.Migration):
-
initial = True
dependencies = []
diff --git a/examples/django/oauth_app/migrations/0002_token_rotation.py b/examples/django/oauth_app/migrations/0002_token_rotation.py
index 65648d6b2..27a67c72d 100644
--- a/examples/django/oauth_app/migrations/0002_token_rotation.py
+++ b/examples/django/oauth_app/migrations/0002_token_rotation.py
@@ -5,7 +5,6 @@
class Migration(migrations.Migration):
-
dependencies = [
("oauth_app", "0001_initial"),
]
diff --git a/examples/docker/aiohttp/Dockerfile b/examples/docker/aiohttp/Dockerfile
index a7b78ed12..7ebb18246 100644
--- a/examples/docker/aiohttp/Dockerfile
+++ b/examples/docker/aiohttp/Dockerfile
@@ -1,13 +1,17 @@
#
# docker build . -t your-repo/hello-bolt
#
-FROM python:3.8.5-slim-buster as builder
+FROM python:3.8-slim-bookworm as builder
RUN apt-get update && apt-get clean
COPY requirements.txt /build/
WORKDIR /build/
RUN pip install -U pip && pip install -r requirements.txt
-FROM python:3.8.5-slim-buster as app
+FROM python:3.8-slim-bookworm as app
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
COPY --from=builder /build/ /app/
COPY --from=builder /usr/local/lib/ /usr/local/lib/
WORKDIR /app/
diff --git a/examples/docker/asgi/Dockerfile b/examples/docker/asgi/Dockerfile
index cef704967..0334461ba 100644
--- a/examples/docker/asgi/Dockerfile
+++ b/examples/docker/asgi/Dockerfile
@@ -1,12 +1,14 @@
#
# docker build . -t your-repo/hello-bolt
#
-FROM python:3.11-alpine3.17 as builder
+FROM python:3.11-alpine3.20 as builder
COPY requirements.txt /build/
WORKDIR /build/
RUN pip install -U pip && pip install -r requirements.txt
-FROM python:3.11-alpine3.17 as app
+FROM python:3.11-alpine3.20 as app
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apk add --no-cache --upgrade ca-certificates ca-certificates-bundle
WORKDIR /app/
COPY --from=builder /usr/local/bin/ /usr/local/bin/
COPY --from=builder /usr/local/lib/ /usr/local/lib/
diff --git a/examples/docker/fastapi-gunicorn/Dockerfile b/examples/docker/fastapi-gunicorn/Dockerfile
index c8f8b94e3..4938b4b5b 100644
--- a/examples/docker/fastapi-gunicorn/Dockerfile
+++ b/examples/docker/fastapi-gunicorn/Dockerfile
@@ -2,6 +2,10 @@
# docker build . -t your-repo/hello-bolt
#
FROM tiangolo/uvicorn-gunicorn:python3.8-slim
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
WORKDIR /app/
COPY *.py /app/
COPY requirements.txt /app/
diff --git a/examples/docker/flask-gunicorn/Dockerfile b/examples/docker/flask-gunicorn/Dockerfile
index e788cb388..a7a0f2362 100644
--- a/examples/docker/flask-gunicorn/Dockerfile
+++ b/examples/docker/flask-gunicorn/Dockerfile
@@ -1,12 +1,16 @@
#
# docker build . -t your-repo/hello-bolt
#
-FROM python:3.8.5-slim-buster as builder
+FROM python:3.8-slim-bookworm as builder
COPY requirements.txt /build/
WORKDIR /build/
RUN pip install -U pip && pip install -r requirements.txt
-FROM python:3.8.5-slim-buster as app
+FROM python:3.8-slim-bookworm as app
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
WORKDIR /app/
COPY --from=builder /usr/local/bin/ /usr/local/bin/
COPY --from=builder /usr/local/lib/ /usr/local/lib/
diff --git a/examples/docker/flask-uwsgi/Dockerfile b/examples/docker/flask-uwsgi/Dockerfile
index 14ddfb41b..f5d7e6863 100644
--- a/examples/docker/flask-uwsgi/Dockerfile
+++ b/examples/docker/flask-uwsgi/Dockerfile
@@ -1,15 +1,19 @@
#
# docker build . -t your-repo/hello-bolt
#
-FROM python:3.8.5-slim-buster as builder
+FROM python:3.8-slim-bookworm as builder
RUN apt-get update \
- && apt-get -y install build-essential libpcre3-dev \
+ && apt-get -y install build-essential libpcre2-dev \
&& apt-get clean
COPY requirements.txt /build/
WORKDIR /build/
RUN pip install -U pip && pip install -r requirements.txt
-FROM python:3.8.5-slim-buster as app
+FROM python:3.8-slim-bookworm as app
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
WORKDIR /app/
COPY --from=builder /usr/local/bin/ /usr/local/bin/
COPY --from=builder /usr/local/lib/ /usr/local/lib/
diff --git a/examples/docker/sanic/Dockerfile b/examples/docker/sanic/Dockerfile
index 4606e68bd..c24d81b5c 100644
--- a/examples/docker/sanic/Dockerfile
+++ b/examples/docker/sanic/Dockerfile
@@ -1,12 +1,16 @@
#
# docker build . -t your-repo/hello-bolt
#
-FROM python:3.8.5-slim-buster as builder
+FROM python:3.8-slim-bookworm as builder
COPY requirements.txt /build/
WORKDIR /build/
RUN pip install -U pip && pip install -r requirements.txt
-FROM python:3.8.5-slim-buster as app
+FROM python:3.8-slim-bookworm as app
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
WORKDIR /app/
COPY *.py /app/
COPY --from=builder /usr/local/bin/ /usr/local/bin/
diff --git a/examples/getting_started/README.md b/examples/getting_started/README.md
index 5d3c2f61d..48f9d4095 100644
--- a/examples/getting_started/README.md
+++ b/examples/getting_started/README.md
@@ -42,6 +42,6 @@ ngrok http 3000
python3 app.py
```
-[1]: https://docs.slack.dev/tools/bolt-python/building-an-app
+[1]: https://docs.slack.dev/tools/bolt-python/creating-an-app
[2]: https://docs.slack.dev/tools/bolt-python/
-[3]: https://docs.slack.dev/tools/bolt-python/building-an-app#setting-up-events
+[3]: https://docs.slack.dev/tools/bolt-python/creating-an-app#setting-up-events
diff --git a/examples/google_app_engine/flask/app.yaml b/examples/google_app_engine/flask/app.yaml
index dfe7de530..ecc2ab272 100644
--- a/examples/google_app_engine/flask/app.yaml
+++ b/examples/google_app_engine/flask/app.yaml
@@ -1,4 +1,4 @@
-runtime: python38
+runtime: python311
inbound_services:
- warmup
diff --git a/examples/google_cloud_functions/oauth_main.py b/examples/google_cloud_functions/oauth_main.py
index 773eafcf3..190f9d000 100644
--- a/examples/google_cloud_functions/oauth_main.py
+++ b/examples/google_cloud_functions/oauth_main.py
@@ -52,6 +52,7 @@ def event_test(body, say, logger):
# Cloud Function
def hello_bolt_app(req: Request):
"""HTTP Cloud Function.
+
Args:
req (flask.Request): The request object.
diff --git a/examples/google_cloud_functions/requirements.txt b/examples/google_cloud_functions/requirements.txt
index 7ebbe8ab2..edcb53ad3 100644
--- a/examples/google_cloud_functions/requirements.txt
+++ b/examples/google_cloud_functions/requirements.txt
@@ -1,3 +1,4 @@
Flask>1
slack_bolt
-google-cloud-datastore>=2.1.0,<3
\ No newline at end of file
+google-cloud-datastore>=2.1.0,<3
+certifi>=2026.10.19
\ No newline at end of file
diff --git a/examples/google_cloud_functions/simple_main.py b/examples/google_cloud_functions/simple_main.py
index 9ff839aca..bab5e85f1 100644
--- a/examples/google_cloud_functions/simple_main.py
+++ b/examples/google_cloud_functions/simple_main.py
@@ -32,6 +32,7 @@ def event_test(body, say, logger):
# Cloud Function
def hello_bolt_app(req: Request):
"""HTTP Cloud Function.
+
Args:
req (flask.Request): The request object.
diff --git a/examples/google_cloud_run/aiohttp/Dockerfile b/examples/google_cloud_run/aiohttp/Dockerfile
index e4432e3a2..77a656180 100644
--- a/examples/google_cloud_run/aiohttp/Dockerfile
+++ b/examples/google_cloud_run/aiohttp/Dockerfile
@@ -11,7 +11,12 @@
# ----------------------------------------------
# Use the official lightweight Python image.
# https://hub.docker.com/_/python
-FROM python:3.8.5-slim-buster
+FROM python:3.8-slim-bookworm
+
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True
diff --git a/examples/google_cloud_run/flask-gunicorn/Dockerfile b/examples/google_cloud_run/flask-gunicorn/Dockerfile
index 8342e3a8b..01dd32523 100644
--- a/examples/google_cloud_run/flask-gunicorn/Dockerfile
+++ b/examples/google_cloud_run/flask-gunicorn/Dockerfile
@@ -11,7 +11,12 @@
# ----------------------------------------------
# Use the official lightweight Python image.
# https://hub.docker.com/_/python
-FROM python:3.8.5-slim-buster
+FROM python:3.8-slim-bookworm
+
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True
diff --git a/examples/google_cloud_run/sanic/Dockerfile b/examples/google_cloud_run/sanic/Dockerfile
index d71ddef67..15c38fe1e 100644
--- a/examples/google_cloud_run/sanic/Dockerfile
+++ b/examples/google_cloud_run/sanic/Dockerfile
@@ -11,7 +11,12 @@
# ----------------------------------------------
# Use the official lightweight Python image.
# https://hub.docker.com/_/python
-FROM python:3.8.5-slim-buster
+FROM python:3.8-slim-bookworm
+
+# Refresh the OS trust store so the image gets the latest ca-certificates.
+RUN apt-get update \
+ && apt-get install -y --no-install-recommends ca-certificates \
+ && rm -rf /var/lib/apt/lists/*
# Allow statements and log messages to immediately appear in the Knative logs
ENV PYTHONUNBUFFERED True
diff --git a/examples/message_events.py b/examples/message_events.py
index 3fd424060..71ef91a4e 100644
--- a/examples/message_events.py
+++ b/examples/message_events.py
@@ -46,8 +46,7 @@ def reply_in_thread(body: dict, say: Say):
event={"type": "message", "subtype": "message_deleted"},
matchers=[
# Skip the deletion of messages by this listener
- lambda body: "You've deleted a message: "
- not in body["event"]["previous_message"]["text"]
+ lambda body: "You've deleted a message: " not in body["event"]["previous_message"]["text"]
],
)
def detect_deletion(say: Say, body: dict):
diff --git a/pyproject.toml b/pyproject.toml
index 88842d0d9..68cc2214e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,9 +4,10 @@ build-backend = "setuptools.build_meta"
[project]
name = "slack_bolt"
-dynamic = ["version", "readme", "authors"]
+dynamic = ["version", "readme"]
description = "The Bolt Framework for Python"
license = { text = "MIT" }
+authors = [{ name = "Slack Technologies, LLC" }, { email = "opensource@slack.com" }]
classifiers = [
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
@@ -16,6 +17,7 @@ classifiers = [
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
+ "Programming Language :: Python :: 3.15",
"Programming Language :: Python :: Implementation :: CPython",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
@@ -25,7 +27,9 @@ dependencies = ["slack_sdk>=3.38.0,<4"]
[project.urls]
+Homepage = "https://github.com/slackapi/bolt-python"
Documentation = "https://docs.slack.dev/tools/bolt-python/"
+Source = "https://github.com/slackapi/bolt-python"
[tool.setuptools.packages.find]
include = ["slack_bolt*"]
@@ -37,9 +41,33 @@ readme = { file = ["README.md"], content-type = "text/markdown" }
[tool.distutils.bdist_wheel]
universal = true
-[tool.black]
+[tool.ruff]
line-length = 125
+[tool.ruff.lint]
+select = ["E", "W", "F", "D"]
+ignore = [
+ "F841",
+ "F821",
+ "E402",
+ # missing-docstring: do not add docstrings where none exist (the only D rules ignored)
+ "D100",
+ "D101",
+ "D102",
+ "D103",
+ "D104",
+ "D105",
+ "D106",
+ "D107",
+]
+
+[tool.ruff.lint.pydocstyle]
+# Keep `select = ["D"]` a bare category select; listing explicit D codes would override this convention.
+convention = "google"
+
+[tool.ruff.format]
+docstring-code-format = true
+
[tool.pytest.ini_options]
testpaths = ["tests"]
log_file = "logs/pytest.log"
diff --git a/requirements/adapter.txt b/requirements/adapter.txt
deleted file mode 100644
index 2564aae79..000000000
--- a/requirements/adapter.txt
+++ /dev/null
@@ -1,30 +0,0 @@
-# pip install -r requirements/adapter.txt
-# NOTE: any of async ones requires pip install -r requirements/async.txt too
-# used only under slack_bolt/adapter
-boto3<=2
-bottle>=0.12,<1
-chalice>=1.28,<1.31; python_version<"3.9"
-chalice>=1.32.0,<2; python_version>="3.9"
-cheroot<12
-CherryPy>=18,<19
-Django>=3,<6
-falcon>=2,<4; python_version<"3.9"
-falcon>=4.2.0,<5; python_version>="3.9"
-fastapi>=0.70.0,<1
-Flask>=1,<4
-Werkzeug>=2,<3; python_version<"3.9"
-Werkzeug>=3.1.8,<4; python_version>="3.9"
-pyramid>=1,<3
-setuptools<82 # Pinned: Pyramid depends on pkg_resources (deprecated in setuptools 67.5.0, removed in 82+). See: https://github.com/Pylons/pyramid/issues/3731
-
-# Sanic and its dependencies
-# Note: Sanic imports tracerite with wild card versions
-tracerite<1.1.2; python_version<="3.8" # older versions of python are not compatible with tracerite>1.1.2
-sanic>=21,<24; python_version<="3.8"
-sanic>=21,<26; python_version>"3.8"
-
-starlette>=0.19.1,<1
-tornado>=6,<7
-uvicorn<1 # The oldest version can vary among Python runtime versions
-gunicorn>=20,<24
-websocket_client>=1.2.3,<2 # Socket Mode 3rd party implementation
diff --git a/requirements/adapter_dev.txt b/requirements/adapter_dev.txt
new file mode 100644
index 000000000..3020354a7
--- /dev/null
+++ b/requirements/adapter_dev.txt
@@ -0,0 +1,80 @@
+# pip install -r requirements/adapter_dev.txt
+# Note: any of the async ones requires pip install -r requirements/async_dev.txt too
+# Note: used only under slack_bolt/adapter
+
+# boto3
+boto3<=2
+
+# bottle
+bottle>=0.13.4,<1
+
+# chalice
+chalice>=1.28,<1.31; python_version < "3.9"
+chalice>=1.32.0,<1.33; python_version >= "3.9" and python_version < "3.10"
+chalice>=1.34.0,<2; python_version >= "3.10"
+
+# cheroot
+cheroot<12
+
+# CherryPy
+CherryPy>=18.10.0,<19
+
+# Django
+# Note: Django 5.x requires Python >=3.10 and 4.x requires >=3.8, so 3.8/3.9 stay on the 4.2 LTS line and 3.7 stays on the 3.2 line.
+Django>=3.2,<4; python_version < "3.8"
+Django>=4.2.30,<5; python_version >= "3.8" and python_version < "3.10"
+Django>=5.2.19,<6; python_version >= "3.10"
+
+# falcon
+# Note: falcon 4.2.0 requires Python >=3.9; 3.7/3.8 stay on the older pinned release.
+falcon>=2,<4; python_version < "3.9"
+falcon>=4.4.0,<5; python_version >= "3.9"
+
+# fastapi
+fastapi>=0.70.0,<1; python_version < "3.9"
+fastapi>=0.128.8,<0.129.0; python_version >= "3.9" and python_version < "3.10"
+fastapi>=0.162.1,<1; python_version >= "3.10"
+
+# Flask
+# Note: Flask 3.1.3 requires Python >=3.9; 3.7/3.8 stay on the older pinned release.
+Flask>=1,<4; python_version < "3.9"
+Flask>=3.1.3,<4; python_version >= "3.9"
+
+# Werkzeug
+# Note: Werkzeug 3.1.8 requires Python >=3.9; 3.7/3.8 stay on the older pinned release.
+Werkzeug>=2,<3; python_version < "3.9"
+Werkzeug>=3.1.8,<4; python_version >= "3.9"
+
+# pyramid
+# Note: pyramid 2.1 requires Python >=3.10; 3.7/3.8/3.9 stay on the last 2.0.x release.
+pyramid>=1,<2.1; python_version < "3.10"
+pyramid>=2.1,<3; python_version >= "3.10"
+
+# setuptools
+# Note: Pyramid depends on pkg_resources (deprecated in setuptools 67.5.0, removed in 82+). See: https://github.com/Pylons/pyramid/issues/3731
+setuptools<82
+
+# sanic
+# Note: Sanic pulls in tracerite via a wildcard version, so tracerite is co-pinned here.
+# Note: tracerite > 1.1.2 is incompatible with Python <= 3.8 and ships no requires_python, so an explicit ceiling is required.
+# Note: sanic 25.12 requires Python >=3.10; 3.9 stays on the older 25.x line.
+tracerite<1.1.2; python_version < "3.9"
+sanic>=21,<24; python_version < "3.9"
+sanic>=25.3.0,<25.12.0; python_version >= "3.9" and python_version < "3.10"
+sanic>=25.12.1,<26; python_version >= "3.10"
+
+# starlette
+starlette>=0.19.1,<0.45; python_version < "3.9"
+starlette>=0.49.3,<0.50; python_version >= "3.9" and python_version < "3.10"
+starlette>=1.7.0,<2; python_version >= "3.10"
+
+# tornado
+# Note: tornado 6.5.6 requires Python >=3.9; 3.7/3.8 stay on the older pinned release.
+tornado>=6.2,<7; python_version < "3.9"
+tornado>=6.5.10,<7; python_version >= "3.9"
+
+# websocket_client
+# Note: Socket Mode 3rd party implementation
+websocket_client>=1.2.3,<1.9; python_version < "3.9"
+websocket_client>=1.9.0,<1.9.1; python_version >= "3.9" and python_version < "3.10"
+websocket_client>=1.9.2,<2; python_version >= "3.10"
diff --git a/requirements/adapter_testing.txt b/requirements/adapter_testing.txt
deleted file mode 100644
index dd4a1cf84..000000000
--- a/requirements/adapter_testing.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-# pip install -r requirements/adapter_testing.txt
-moto>=3,<6 # For AWS tests
-docker>=5,<8 # Used by moto
-boddle>=0.2.9,<0.3 # For Bottle app tests
-sanic-testing>=0.7
diff --git a/requirements/async.txt b/requirements/async.txt
deleted file mode 100644
index af3e49913..000000000
--- a/requirements/async.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-# pip install -r requirements/async.txt
-aiohttp>=3,<4
-websockets<16
diff --git a/requirements/async_dev.txt b/requirements/async_dev.txt
new file mode 100644
index 000000000..29d0efc59
--- /dev/null
+++ b/requirements/async_dev.txt
@@ -0,0 +1,13 @@
+# pip install -r requirements/async_dev.txt
+
+# aiohttp
+# Newer aiohttp releases drop older Python versions, so each one gets its own floor:
+# - Python 3.7 and 3.8: any aiohttp 3.x
+# - Python 3.9: aiohttp 3.13.5 or later
+# - Python 3.10 and later: aiohttp 3.14.5 or later
+aiohttp>=3,<4; python_version < "3.9"
+aiohttp>=3.13.5,<4; python_version == "3.9"
+aiohttp>=3.14.5,<4; python_version >= "3.10"
+
+# websockets
+websockets<17
diff --git a/requirements/dev_tools.txt b/requirements/dev_tools.txt
new file mode 100644
index 000000000..94780cda6
--- /dev/null
+++ b/requirements/dev_tools.txt
@@ -0,0 +1,7 @@
+# pip install -r requirements/dev_tools.txt
+
+# mypy
+mypy==2.4.1
+
+# ruff
+ruff==0.17.3
diff --git a/requirements/test.txt b/requirements/test.txt
new file mode 100644
index 000000000..af895692b
--- /dev/null
+++ b/requirements/test.txt
@@ -0,0 +1,8 @@
+# pip install -r requirements/test.txt
+
+# pytest
+pytest<9.2
+
+# pytest-cov
+# Note: only needed to evaluate coverage on the latest supported python version
+pytest-cov>=7.1.0,<8; python_version >= "3.14"
diff --git a/requirements/test_adapter.txt b/requirements/test_adapter.txt
new file mode 100644
index 000000000..73a934fb9
--- /dev/null
+++ b/requirements/test_adapter.txt
@@ -0,0 +1,16 @@
+# pip install -r requirements/test_adapter.txt
+
+# moto
+# Note: for AWS tests
+# Note: moto drops old Pythons across the 5.x line — 5.0.0 requires >=3.8, 5.1.0 >=3.9, 5.2.0 >=3.10; older interpreters stay on the last compatible release.
+moto>=3,<5; python_version < "3.8"
+moto>=3,<5.1; python_version >= "3.8" and python_version < "3.9"
+moto>=3,<5.2; python_version >= "3.9" and python_version < "3.10"
+moto>=5.2.5,<6; python_version >= "3.10"
+
+# boddle
+# Note: for Bottle app tests
+boddle>=0.2.9,<0.3
+
+# sanic-testing
+sanic-testing>=24.6.0
diff --git a/requirements/test_async.txt b/requirements/test_async.txt
new file mode 100644
index 000000000..3d1b3ab4c
--- /dev/null
+++ b/requirements/test_async.txt
@@ -0,0 +1,11 @@
+# pip install -r requirements/test_async.txt
+-r test.txt
+-r async_dev.txt
+
+# asgiref
+asgiref>=3.7.2,<3.8; python_version < "3.9"
+asgiref>=3.11.1,<3.12; python_version >= "3.9" and python_version < "3.10"
+asgiref>=3.12.1,<4; python_version >= "3.10"
+
+# pytest-asyncio
+pytest-asyncio<2
diff --git a/requirements/testing.txt b/requirements/testing.txt
deleted file mode 100644
index 62fdcca2d..000000000
--- a/requirements/testing.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-# pip install -r requirements/testing.txt
--r testing_without_asyncio.txt
--r async.txt
-pytest-asyncio<2;
diff --git a/requirements/testing_without_asyncio.txt b/requirements/testing_without_asyncio.txt
deleted file mode 100644
index 441b49f8b..000000000
--- a/requirements/testing_without_asyncio.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-# pip install -r requirements/testing_without_asyncio.txt
-pytest<8.5
-pytest-cov>=3,<8
diff --git a/requirements/tools.txt b/requirements/tools.txt
deleted file mode 100644
index dd13bd614..000000000
--- a/requirements/tools.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-mypy==1.19.1
-flake8==7.3.0
-black==26.3.1
diff --git a/scripts/format.sh b/scripts/format.sh
index e73bcdac4..92fe05dde 100755
--- a/scripts/format.sh
+++ b/scripts/format.sh
@@ -7,7 +7,8 @@ cd ${script_dir}/..
if [[ "$1" != "--no-install" ]]; then
export PIP_REQUIRE_VIRTUALENV=1
pip install -U pip
- pip install -U -r requirements/tools.txt
+ pip install -U -r requirements/dev_tools.txt
fi
-black slack_bolt/ tests/
+ruff check --fix slack_bolt/ examples/
+ruff format slack_bolt/ tests/ examples/
diff --git a/scripts/generate_api_docs.sh b/scripts/generate_api_docs.sh
index c3b9fd260..275aa0fe1 100755
--- a/scripts/generate_api_docs.sh
+++ b/scripts/generate_api_docs.sh
@@ -6,8 +6,8 @@ script_dir=$(dirname "$0")
cd "${script_dir}/.."
pip install -U pip
-pip install -U -r requirements/adapter.txt
-pip install -U -r requirements/async.txt
+pip install -U -r requirements/adapter_dev.txt
+pip install -U -r requirements/async_dev.txt
pip install -U pdoc3
pip install .
rm -rf docs/reference
diff --git a/scripts/install.sh b/scripts/install.sh
index 96159c63c..64cdf1561 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -13,10 +13,10 @@ pip install -U pip
pip uninstall python-lambda
pip install -U -e .
-pip install -U -r requirements/testing.txt
-pip install -U -r requirements/adapter.txt
-pip install -U -r requirements/adapter_testing.txt
-pip install -U -r requirements/tools.txt
+pip install -U -r requirements/test_async.txt
+pip install -U -r requirements/adapter_dev.txt
+pip install -U -r requirements/test_adapter.txt
+pip install -U -r requirements/dev_tools.txt
# To avoid errors due to the old versions of click forced by Chalice
pip install -U pip click
diff --git a/scripts/install_all_and_run_tests.sh b/scripts/install_all_and_run_tests.sh
index 939e71ffd..d4601df0c 100755
--- a/scripts/install_all_and_run_tests.sh
+++ b/scripts/install_all_and_run_tests.sh
@@ -9,7 +9,7 @@ cd ${script_dir}/..
test_target="${1:-tests/}"
# keep in sync with LATEST_SUPPORTED_PY in .github/workflows/ci-build.yml
-LATEST_SUPPORTED_PY="3.14"
+LATEST_SUPPORTED_PY="3.15"
current_py=$(python --version | sed -E 's/Python ([0-9]+\.[0-9]+).*/\1/')
./scripts/install.sh
diff --git a/scripts/lint.sh b/scripts/lint.sh
index efee01ebc..c6176d0d1 100755
--- a/scripts/lint.sh
+++ b/scripts/lint.sh
@@ -6,7 +6,8 @@ cd ${script_dir}/..
if [[ "$1" != "--no-install" ]]; then
pip install -U pip
- pip install -U -r requirements/tools.txt
+ pip install -U -r requirements/dev_tools.txt
fi
-flake8 slack_bolt/ && flake8 examples/
+ruff check slack_bolt/ examples/
+ruff format --check slack_bolt/ tests/ examples/
diff --git a/scripts/run_mypy.sh b/scripts/run_mypy.sh
index 27589b348..c9234f87a 100755
--- a/scripts/run_mypy.sh
+++ b/scripts/run_mypy.sh
@@ -7,9 +7,9 @@ cd ${script_dir}/..
if [[ "$1" != "--no-install" ]]; then
pip install -U pip
pip install -U .
- pip install -U -r requirements/async.txt
- pip install -U -r requirements/adapter.txt
- pip install -U -r requirements/tools.txt
+ pip install -U -r requirements/async_dev.txt
+ pip install -U -r requirements/adapter_dev.txt
+ pip install -U -r requirements/dev_tools.txt
fi
mypy --config-file pyproject.toml
diff --git a/setup.cfg b/setup.cfg
deleted file mode 100644
index 3b05a6fa3..000000000
--- a/setup.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
-; Legacy package configuration, prefer pyproject.toml over setup.cfg
-[metadata]
-url=https://github.com/slackapi/bolt-python
-author=Slack Technologies, LLC
-author_email=opensource@slack.com
diff --git a/slack_bolt/__init__.py b/slack_bolt/__init__.py
index d85453950..73336725b 100644
--- a/slack_bolt/__init__.py
+++ b/slack_bolt/__init__.py
@@ -1,5 +1,4 @@
-"""
-A Python framework to build Slack apps in a flash with the latest platform features.Read the [getting started guide](https://docs.slack.dev/tools/bolt-python/building-an-app) and look at our [code examples](https://github.com/slackapi/bolt-python/tree/main/examples) to learn how to build apps using Bolt.
+"""A Python framework to build Slack apps in a flash with the latest platform features. Read the [getting started guide](https://docs.slack.dev/tools/bolt-python/creating-an-app) and look at our [code examples](https://github.com/slackapi/bolt-python/tree/main/examples) to learn how to build apps using Bolt.
* Website: https://docs.slack.dev/tools/bolt-python/
* GitHub repository: https://github.com/slackapi/bolt-python
diff --git a/slack_bolt/adapter/asgi/aiohttp/__init__.py b/slack_bolt/adapter/asgi/aiohttp/__init__.py
index aed8458d9..796098537 100644
--- a/slack_bolt/adapter/asgi/aiohttp/__init__.py
+++ b/slack_bolt/adapter/asgi/aiohttp/__init__.py
@@ -12,6 +12,7 @@ class AsyncSlackRequestHandler(SlackRequestHandler):
def __init__(self, app: AsyncApp, path: str = "/slack/events"):
"""Setup Bolt as an ASGI web framework, this will make your application compatible with ASGI web servers.
+
This can be used for production deployment.
With the default settings, `http://localhost:3000/slack/events`
diff --git a/slack_bolt/adapter/asgi/base_handler.py b/slack_bolt/adapter/asgi/base_handler.py
index 5e68c51f4..2926796a7 100644
--- a/slack_bolt/adapter/asgi/base_handler.py
+++ b/slack_bolt/adapter/asgi/base_handler.py
@@ -1,4 +1,4 @@
-from typing import Callable, Dict, Union
+from typing import Callable, Union
from .http_request import AsgiHttpRequest
from .http_response import AsgiHttpResponse
@@ -18,15 +18,15 @@ class BaseSlackRequestHandler:
path: str
async def dispatch(self, request: AsgiHttpRequest) -> BoltResponse:
- """Dispatches a request to the Bolt App"""
+ """Dispatches a request to the Bolt App."""
raise NotImplementedError
async def handle_installation(self, request: AsgiHttpRequest) -> BoltResponse:
- """Handles installation of the OAuthFlow"""
+ """Handles installation of the OAuthFlow."""
raise NotImplementedError
async def handle_callback(self, request: AsgiHttpRequest) -> BoltResponse:
- """Handles the callback of the OAuthFlow"""
+ """Handles the callback of the OAuthFlow."""
raise NotImplementedError
async def _get_http_response(self, method: str, path: str, request: AsgiHttpRequest) -> AsgiHttpResponse:
@@ -47,25 +47,23 @@ async def _get_http_response(self, method: str, path: str, request: AsgiHttpRequ
return AsgiHttpResponse(status=bolt_response.status, headers=bolt_response.headers, body=bolt_response.body)
return AsgiHttpResponse(status=404, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Not Found")
- async def _handle_lifespan(self, receive: Callable) -> Dict[str, str]:
- while True:
- lifespan = await receive()
- if lifespan["type"] == "lifespan.startup":
- """Do something before startup"""
- return {"type": "lifespan.startup.complete"}
- if lifespan["type"] == "lifespan.shutdown":
- """Do something before shutdown"""
- return {"type": "lifespan.shutdown.complete"}
+ async def _handle_lifespan(self, receive: Callable, send: Callable) -> None:
+ message = await receive()
+ if message["type"] == "lifespan.startup":
+ await send({"type": "lifespan.startup.complete"})
+ message = await receive()
+ if message["type"] == "lifespan.shutdown":
+ await send({"type": "lifespan.shutdown.complete"})
async def __call__(self, scope: scope_type, receive: Callable, send: Callable) -> None:
if scope["type"] == "http":
response: AsgiHttpResponse = await self._get_http_response(
method=scope["method"], path=scope["path"], request=AsgiHttpRequest(scope, receive) # type: ignore[arg-type]
- )
+ ) # fmt: skip
await send(response.get_response_start())
await send(response.get_response_body())
return
if scope["type"] == "lifespan":
- await send(await self._handle_lifespan(receive))
+ await self._handle_lifespan(receive, send)
return
raise TypeError(f"Unsupported scope type: {scope['type']!r}")
diff --git a/slack_bolt/adapter/asgi/builtin/__init__.py b/slack_bolt/adapter/asgi/builtin/__init__.py
index 93f7ab845..b05451f34 100644
--- a/slack_bolt/adapter/asgi/builtin/__init__.py
+++ b/slack_bolt/adapter/asgi/builtin/__init__.py
@@ -11,6 +11,7 @@
class SlackRequestHandler(BaseSlackRequestHandler):
def __init__(self, app: App, path: str = "/slack/events"):
"""Setup Bolt as an ASGI web framework, this will make your application compatible with ASGI web servers.
+
This can be used for production deployment.
With the default settings, `http://localhost:3000/slack/events`
diff --git a/slack_bolt/adapter/asgi/http_response.py b/slack_bolt/adapter/asgi/http_response.py
index c8178b8f5..58969f137 100644
--- a/slack_bolt/adapter/asgi/http_response.py
+++ b/slack_bolt/adapter/asgi/http_response.py
@@ -8,11 +8,14 @@ class AsgiHttpResponse:
def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""):
self.status: int = status
- self.raw_headers: List[Tuple[bytes, bytes]] = [
- (bytes(key, ENCODING), bytes(value[0], ENCODING)) for key, value in headers.items()
- ]
- self.raw_headers.append((b"content-length", bytes(str(len(body)), ENCODING)))
self.body: bytes = bytes(body, ENCODING)
+ self.raw_headers: List[Tuple[bytes, bytes]] = []
+ for key, values in headers.items():
+ if key.lower() == "content-length":
+ continue
+ for v in values:
+ self.raw_headers.append((bytes(key, ENCODING), bytes(v, ENCODING)))
+ self.raw_headers.append((b"content-length", bytes(str(len(self.body)), ENCODING)))
def get_response_start(self) -> Dict[str, Union[str, int, Iterable[Tuple[bytes, bytes]]]]:
return {
diff --git a/slack_bolt/adapter/aws_lambda/handler.py b/slack_bolt/adapter/aws_lambda/handler.py
index 4d155e58f..088055af1 100644
--- a/slack_bolt/adapter/aws_lambda/handler.py
+++ b/slack_bolt/adapter/aws_lambda/handler.py
@@ -57,6 +57,8 @@ def handle(self, event, context):
aws_lambda_function_name = context.function_name
bolt_req.context["aws_lambda_function_name"] = aws_lambda_function_name
bolt_req.context["aws_lambda_invoked_function_arn"] = context.invoked_function_arn
+ bolt_req.context["aws_lambda_request_id"] = context.aws_request_id
+ bolt_req.context["aws_lambda_log_stream_name"] = context.log_stream_name
bolt_req.context["lambda_request"] = event
bolt_resp = self.app.dispatch(bolt_req)
aws_response = to_aws_response(bolt_resp)
@@ -71,22 +73,22 @@ def handle(self, event, context):
def to_bolt_request(event) -> BoltRequest:
- body = event.get("body", "")
- if event["isBase64Encoded"]:
+ body = event.get("body") or ""
+ if event.get("isBase64Encoded") is True and body:
body = base64.b64decode(body).decode("utf-8")
- cookies: Sequence[str] = event.get("cookies", [])
- if cookies is None or len(cookies) == 0:
+ cookies: Sequence[str] = event.get("cookies") or []
+ if len(cookies) == 0:
# In the case of format v1
- multiValueHeaders = event.get("multiValueHeaders", {})
- cookies = multiValueHeaders.get("cookie", [])
+ multiValueHeaders = event.get("multiValueHeaders") or {}
+ cookies = multiValueHeaders.get("cookie") or []
if len(cookies) == 0:
# Try using uppercase
- cookies = multiValueHeaders.get("Cookie", [])
- headers = event.get("headers", {})
+ cookies = multiValueHeaders.get("Cookie") or []
+ headers = dict(event.get("headers") or {})
headers["cookie"] = cookies
return BoltRequest(
body=body,
- query=event.get("queryStringParameters", {}),
+ query=event.get("queryStringParameters") or {},
headers=headers,
)
diff --git a/slack_bolt/adapter/django/handler.py b/slack_bolt/adapter/django/handler.py
index 4ede5fde3..b01323a10 100644
--- a/slack_bolt/adapter/django/handler.py
+++ b/slack_bolt/adapter/django/handler.py
@@ -66,13 +66,13 @@ def release_thread_local_connections(logger: Logger, execution_timing: str):
if logger.level <= logging.DEBUG:
current: Thread = current_thread()
logger.debug(
- "Released thread-bound old DB connections "
- f"(thread name: {current.name}, execution timing: {execution_timing})"
+ f"Released thread-bound old DB connections (thread name: {current.name}, execution timing: {execution_timing})"
)
class DjangoListenerStartHandler(ListenerStartHandler):
"""Django sets DB connections as a thread-local variable per thread.
+
If the thread is not managed on the Django app side, the connections won't be released by Django.
This handler releases the connections every time a ThreadListenerRunner execution completes.
"""
@@ -83,6 +83,7 @@ def handle(self, request: BoltRequest, response: Optional[BoltResponse]) -> None
class DjangoListenerCompletionHandler(ListenerCompletionHandler):
"""Django sets DB connections as a thread-local variable per thread.
+
If the thread is not managed on the Django app side, the connections won't be released by Django.
This handler releases the connections every time a ThreadListenerRunner execution completes.
"""
diff --git a/slack_bolt/adapter/falcon/async_resource.py b/slack_bolt/adapter/falcon/async_resource.py
index 8d03b456c..1c22c83a0 100644
--- a/slack_bolt/adapter/falcon/async_resource.py
+++ b/slack_bolt/adapter/falcon/async_resource.py
@@ -1,6 +1,7 @@
from datetime import datetime
from http import HTTPStatus
+from falcon import MEDIA_TEXT
from falcon import version as falcon_version
from falcon.asgi import Request, Response
from slack_bolt import BoltResponse
@@ -11,8 +12,7 @@
class AsyncSlackAppResource:
- """
- For use with ASGI Falcon Apps.
+ """For use with ASGI Falcon Apps.
from slack_bolt.async_app import AsyncApp
app = AsyncApp()
@@ -40,9 +40,9 @@ async def on_get(self, req: Request, resp: Response):
await self._write_response(bolt_resp, resp)
return
- resp.status = "404"
- # Falcon 4.x w/ mypy fails to correctly infer the str type here
- resp.body = "The page is not found..."
+ resp.status = HTTPStatus.NOT_FOUND
+ resp.content_type = MEDIA_TEXT
+ resp.text = "The page is not found..."
async def on_post(self, req: Request, resp: Response):
bolt_req = await self._to_bolt_request(req)
diff --git a/slack_bolt/adapter/falcon/resource.py b/slack_bolt/adapter/falcon/resource.py
index 53792775f..f80338755 100644
--- a/slack_bolt/adapter/falcon/resource.py
+++ b/slack_bolt/adapter/falcon/resource.py
@@ -1,6 +1,7 @@
from datetime import datetime
from http import HTTPStatus
+from falcon import MEDIA_TEXT
from falcon import Request, Response, version as falcon_version
from slack_bolt import BoltResponse
@@ -10,7 +11,8 @@
class SlackAppResource:
- """
+ """For use with WSGI Falcon Apps.
+
from slack_bolt import App
app = App()
@@ -34,9 +36,9 @@ def on_get(self, req: Request, resp: Response):
self._write_response(bolt_resp, resp)
return
- resp.status = "404"
- # Falcon 4.x w/ mypy fails to correctly infer the str type here
- resp.body = "The page is not found..."
+ resp.status = HTTPStatus.NOT_FOUND
+ resp.content_type = MEDIA_TEXT
+ resp.text = "The page is not found..."
def on_post(self, req: Request, resp: Response):
bolt_req = self._to_bolt_request(req)
diff --git a/slack_bolt/adapter/socket_mode/aiohttp/__init__.py b/slack_bolt/adapter/socket_mode/aiohttp/__init__.py
index 124daaa4a..b117df790 100644
--- a/slack_bolt/adapter/socket_mode/aiohttp/__init__.py
+++ b/slack_bolt/adapter/socket_mode/aiohttp/__init__.py
@@ -1,4 +1,4 @@
-"""[`aiohttp`](https://pypi.org/project/aiohttp/) based implementation / asyncio compatible"""
+"""[`aiohttp`](https://pypi.org/project/aiohttp/) based implementation / asyncio compatible."""
import os
from logging import Logger
@@ -35,7 +35,7 @@ def __init__(
proxy: Optional[str] = None,
ping_interval: float = 10,
):
- """Socket Mode adapter for Bolt apps
+ """Socket Mode adapter for Bolt apps.
Args:
app: The Bolt app
diff --git a/slack_bolt/adapter/socket_mode/async_base_handler.py b/slack_bolt/adapter/socket_mode/async_base_handler.py
index 32ddaff14..2a8355ba4 100644
--- a/slack_bolt/adapter/socket_mode/async_base_handler.py
+++ b/slack_bolt/adapter/socket_mode/async_base_handler.py
@@ -1,4 +1,4 @@
-"""The base class of asyncio-based Socket Mode client implementation"""
+"""The base class of asyncio-based Socket Mode client implementation."""
import asyncio
import logging
@@ -26,20 +26,20 @@ async def handle(self, client: AsyncBaseSocketModeClient, req: SocketModeRequest
raise NotImplementedError()
async def connect_async(self):
- """Establishes a new connection with the Socket Mode server"""
+ """Establishes a new connection with the Socket Mode server."""
await self.client.connect()
async def disconnect_async(self):
- """Disconnects the current WebSocket connection with the Socket Mode server"""
+ """Disconnects the current WebSocket connection with the Socket Mode server."""
await self.client.disconnect()
async def close_async(self):
- """Disconnects from the Socket Mode server and cleans the resources this instance holds up"""
+ """Disconnects from the Socket Mode server and cleans the resources this instance holds up."""
await self.client.close()
async def start_async(self):
- """Establishes a new connection and then starts infinite sleep
- to prevent the termination of this process.
+ """Establishes a new connection and then starts infinite sleep to prevent the termination of this process.
+
If you don't want to have the sleep, use `#connect()` method instead.
"""
await self.connect_async()
diff --git a/slack_bolt/adapter/socket_mode/async_internals.py b/slack_bolt/adapter/socket_mode/async_internals.py
index c2965f766..5fefd7400 100644
--- a/slack_bolt/adapter/socket_mode/async_internals.py
+++ b/slack_bolt/adapter/socket_mode/async_internals.py
@@ -1,4 +1,4 @@
-"""Internal functions"""
+"""Internal functions."""
import json
import logging
@@ -8,13 +8,14 @@
from slack_sdk.socket_mode.request import SocketModeRequest
from slack_sdk.socket_mode.response import SocketModeResponse
+from slack_bolt.adapter.socket_mode.internals import build_headers
from slack_bolt.app.async_app import AsyncApp
from slack_bolt.request.async_request import AsyncBoltRequest
from slack_bolt.response import BoltResponse
async def run_async_bolt_app(app: AsyncApp, req: SocketModeRequest):
- bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload)
+ bolt_req: AsyncBoltRequest = AsyncBoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
bolt_resp: BoltResponse = await app.async_dispatch(bolt_req)
return bolt_resp
diff --git a/slack_bolt/adapter/socket_mode/base_handler.py b/slack_bolt/adapter/socket_mode/base_handler.py
index 432a327b9..cf74fed2c 100644
--- a/slack_bolt/adapter/socket_mode/base_handler.py
+++ b/slack_bolt/adapter/socket_mode/base_handler.py
@@ -1,4 +1,5 @@
"""The base class of Socket Mode client implementation.
+
If you want to build asyncio-based ones, use `AsyncBaseSocketModeHandler` instead.
"""
@@ -28,20 +29,20 @@ def handle(self, client: BaseSocketModeClient, req: SocketModeRequest) -> None:
raise NotImplementedError()
def connect(self):
- """Establishes a new connection with the Socket Mode server"""
+ """Establishes a new connection with the Socket Mode server."""
self.client.connect()
def disconnect(self):
- """Disconnects the current WebSocket connection with the Socket Mode server"""
+ """Disconnects the current WebSocket connection with the Socket Mode server."""
self.client.disconnect()
def close(self):
- """Disconnects from the Socket Mode server and cleans the resources this instance holds up"""
+ """Disconnects from the Socket Mode server and cleans the resources this instance holds up."""
self.client.close()
def start(self):
- """Establishes a new connection and then blocks the current thread
- to prevent the termination of this process.
+ """Establishes a new connection and then blocks the current thread to prevent the termination of this process.
+
If you don't want to block the current thread, use `#connect()` method instead.
"""
self.connect()
diff --git a/slack_bolt/adapter/socket_mode/builtin/__init__.py b/slack_bolt/adapter/socket_mode/builtin/__init__.py
index 6dbc9562d..397724039 100644
--- a/slack_bolt/adapter/socket_mode/builtin/__init__.py
+++ b/slack_bolt/adapter/socket_mode/builtin/__init__.py
@@ -1,4 +1,4 @@
-"""The built-in implementation, which does not have any external dependencies"""
+"""The built-in implementation, which does not have any external dependencies."""
import os
from logging import Logger
@@ -36,7 +36,7 @@ def __init__(
receive_buffer_size: int = 1024,
concurrency: int = 10,
):
- """Socket Mode adapter for Bolt apps
+ """Socket Mode adapter for Bolt apps.
Args:
app: The Bolt app
diff --git a/slack_bolt/adapter/socket_mode/internals.py b/slack_bolt/adapter/socket_mode/internals.py
index 8eb751b4d..b57a1c3d7 100644
--- a/slack_bolt/adapter/socket_mode/internals.py
+++ b/slack_bolt/adapter/socket_mode/internals.py
@@ -1,8 +1,9 @@
-"""Internal functions"""
+"""Internal functions."""
import json
import logging
from time import time
+from typing import Dict, Optional, Sequence, Union
from slack_sdk.socket_mode.client import BaseSocketModeClient
from slack_sdk.socket_mode.request import SocketModeRequest
@@ -13,8 +14,18 @@
from slack_bolt.response import BoltResponse
+def build_headers(req: SocketModeRequest) -> Optional[Dict[str, Union[str, Sequence[str]]]]:
+ # Mirror the HTTP mode retry headers so middleware/listeners can detect Events API retries
+ headers: Dict[str, Union[str, Sequence[str]]] = {}
+ if req.retry_attempt is not None:
+ headers["x-slack-retry-num"] = str(req.retry_attempt)
+ if req.retry_reason is not None:
+ headers["x-slack-retry-reason"] = req.retry_reason
+ return headers or None
+
+
def run_bolt_app(app: App, req: SocketModeRequest):
- bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload)
+ bolt_req: BoltRequest = BoltRequest(mode="socket_mode", body=req.payload, headers=build_headers(req))
bolt_resp: BoltResponse = app.dispatch(bolt_req)
return bolt_resp
diff --git a/slack_bolt/adapter/socket_mode/websocket_client/__init__.py b/slack_bolt/adapter/socket_mode/websocket_client/__init__.py
index aae549ad6..b6acac619 100644
--- a/slack_bolt/adapter/socket_mode/websocket_client/__init__.py
+++ b/slack_bolt/adapter/socket_mode/websocket_client/__init__.py
@@ -1,4 +1,4 @@
-"""[`websocket-client`](https://pypi.org/project/websocket-client/) based implementation"""
+"""[`websocket-client`](https://pypi.org/project/websocket-client/) based implementation."""
import os
from logging import Logger
@@ -34,7 +34,7 @@ def __init__(
proxy_type: Optional[str] = None,
trace_enabled: bool = False,
):
- """Socket Mode adapter for Bolt apps
+ """Socket Mode adapter for Bolt apps.
Args:
app: The Bolt app
diff --git a/slack_bolt/adapter/socket_mode/websockets/__init__.py b/slack_bolt/adapter/socket_mode/websockets/__init__.py
index 049a20570..ce1665c5d 100644
--- a/slack_bolt/adapter/socket_mode/websockets/__init__.py
+++ b/slack_bolt/adapter/socket_mode/websockets/__init__.py
@@ -1,4 +1,4 @@
-"""[`websockets`](https://pypi.org/project/websockets/) based implementation / asyncio compatible"""
+"""[`websockets`](https://pypi.org/project/websockets/) based implementation / asyncio compatible."""
import os
from logging import Logger
diff --git a/slack_bolt/adapter/wsgi/handler.py b/slack_bolt/adapter/wsgi/handler.py
index 2861b4425..b13e64530 100644
--- a/slack_bolt/adapter/wsgi/handler.py
+++ b/slack_bolt/adapter/wsgi/handler.py
@@ -1,6 +1,10 @@
-from typing import Any, Callable, Dict, Iterable, List, Tuple
+from typing import TYPE_CHECKING, Iterable
from slack_bolt import App
+
+if TYPE_CHECKING:
+ from wsgiref.types import StartResponse, WSGIEnvironment
+
from slack_bolt.adapter.wsgi.http_request import WsgiHttpRequest
from slack_bolt.adapter.wsgi.http_response import WsgiHttpResponse
from slack_bolt.request import BoltRequest
@@ -10,6 +14,7 @@
class SlackRequestHandler:
def __init__(self, app: App, path: str = "/slack/events"):
"""Setup Bolt as a WSGI web framework, this will make your application compatible with WSGI web servers.
+
This can be used for production deployments.
With the default settings, `http://localhost:3000/slack/events`
@@ -69,14 +74,17 @@ def _get_http_response(self, request: WsgiHttpRequest) -> WsgiHttpResponse:
def __call__(
self,
- environ: Dict[str, Any],
- start_response: Callable[[str, List[Tuple[str, str]]], None],
+ environ: "WSGIEnvironment",
+ start_response: "StartResponse",
) -> Iterable[bytes]:
request = WsgiHttpRequest(environ)
- if "HTTP" in request.protocol:
+ if request.protocol.startswith("HTTP"):
response: WsgiHttpResponse = self._get_http_response(
request=request,
)
- start_response(response.status, response.get_headers())
- return response.get_body()
- raise TypeError(f"Unsupported SERVER_PROTOCOL: {request.protocol}")
+ else:
+ response = WsgiHttpResponse(
+ status=400, headers={"content-type": ["text/plain;charset=utf-8"]}, body="Bad Request"
+ )
+ start_response(response.status, response.get_headers())
+ return response.get_body()
diff --git a/slack_bolt/adapter/wsgi/http_request.py b/slack_bolt/adapter/wsgi/http_request.py
index 460d8f531..ac4c434bd 100644
--- a/slack_bolt/adapter/wsgi/http_request.py
+++ b/slack_bolt/adapter/wsgi/http_request.py
@@ -1,18 +1,20 @@
-from typing import Any, Dict, Sequence, Union
+from typing import TYPE_CHECKING, Dict, Sequence, Union
+
+if TYPE_CHECKING:
+ from wsgiref.types import WSGIEnvironment
from .internals import ENCODING
class WsgiHttpRequest:
- """This Class uses the PEP 3333 standard to extract request information
- from the WSGI web server running the application
+ """Extracts request information from the WSGI web server using the PEP 3333 standard.
PEP 3333: https://peps.python.org/pep-3333/
"""
__slots__ = ("method", "path", "query_string", "protocol", "environ")
- def __init__(self, environ: Dict[str, Any]):
+ def __init__(self, environ: "WSGIEnvironment"):
self.method: str = environ.get("REQUEST_METHOD", "GET")
self.path: str = environ.get("PATH_INFO", "")
self.query_string: str = environ.get("QUERY_STRING", "")
@@ -33,5 +35,5 @@ def get_headers(self) -> Dict[str, Union[str, Sequence[str]]]:
def get_body(self) -> str:
if "wsgi.input" not in self.environ:
return ""
- content_length = int(self.environ.get("CONTENT_LENGTH", 0))
+ content_length = int(self.environ.get("CONTENT_LENGTH") or 0)
return self.environ["wsgi.input"].read(content_length).decode(ENCODING)
diff --git a/slack_bolt/adapter/wsgi/http_response.py b/slack_bolt/adapter/wsgi/http_response.py
index 1ad32e672..32feff3d0 100644
--- a/slack_bolt/adapter/wsgi/http_response.py
+++ b/slack_bolt/adapter/wsgi/http_response.py
@@ -1,30 +1,30 @@
from http import HTTPStatus
-from typing import Dict, Iterable, List, Sequence, Tuple
+from typing import Dict, Iterable, List, Optional, Sequence, Tuple
from .internals import ENCODING
class WsgiHttpResponse:
- """This Class uses the PEP 3333 standard to adapt bolt response information
- for the WSGI web server running the application
+ """Adapts bolt response information for the WSGI web server using the PEP 3333 standard.
PEP 3333: https://peps.python.org/pep-3333/
"""
__slots__ = ("status", "_headers", "_body")
- def __init__(self, status: int, headers: Dict[str, Sequence[str]] = {}, body: str = ""):
+ def __init__(self, status: int, headers: Optional[Dict[str, Sequence[str]]] = None, body: str = ""):
_status = HTTPStatus(status)
self.status = f"{_status.value} {_status.phrase}"
- self._headers = headers
+ self._headers = headers or {}
self._body = bytes(body, ENCODING)
def get_headers(self) -> List[Tuple[str, str]]:
headers: List[Tuple[str, str]] = []
- for key, value in self._headers.items():
+ for key, values in self._headers.items():
if key.lower() == "content-length":
continue
- headers.append((key, value[0]))
+ for v in values:
+ headers.append((key, v))
headers.append(("content-length", str(len(self._body))))
return headers
diff --git a/slack_bolt/app/__init__.py b/slack_bolt/app/__init__.py
index 455f2b949..d5d4f7f8a 100644
--- a/slack_bolt/app/__init__.py
+++ b/slack_bolt/app/__init__.py
@@ -1,4 +1,4 @@
-# flake8: noqa
+# ruff: noqa
"""Application interface in Bolt.
For most use cases, we recommend using `slack_bolt.app.app`.
diff --git a/slack_bolt/app/app.py b/slack_bolt/app/app.py
index 0af27913c..cbaa340f7 100644
--- a/slack_bolt/app/app.py
+++ b/slack_bolt/app/app.py
@@ -156,7 +156,7 @@ def message_hello(message, say):
if __name__ == "__main__":
app.start(port=int(os.environ.get("PORT", 3000)))
- Refer to https://docs.slack.dev/tools/bolt-python/building-an-app for details.
+ Refer to https://docs.slack.dev/tools/bolt-python/creating-an-app for details.
If you would like to build an OAuth app for enabling the app to run with multiple workspaces,
refer to https://docs.slack.dev/tools/bolt-python/concepts/authenticating-oauth to learn how to configure the app.
@@ -207,6 +207,10 @@ def message_hello(message, say):
be used.
assistant_thread_context_store: Custom AssistantThreadContext store (Default: the built-in implementation,
which uses a parent message's metadata to store the latest context)
+ attaching_conversation_kwargs_enabled: False if you would like to disable the built-in
+ middleware (Default: True). `AttachingConversationKwargs` is a built-in middleware that attaches
+ conversation-specific listener arguments (such as `say`, `set_status`, `say_stream`, and
+ `set_suggested_prompts`) for assistant thread and direct message events.
"""
if signing_secret is None:
signing_secret = os.environ.get("SLACK_SIGNING_SECRET", "")
@@ -468,7 +472,7 @@ def _init_middleware_list(
@property
def name(self) -> str:
- """The name of this app (default: the filename)"""
+ """The name of this app (default: the filename)."""
return self._name
@property
@@ -589,7 +593,7 @@ def middleware_next():
# run all the middleware attached to this listener first
middleware_resp, next_was_not_called = listener.run_middleware(
req=req, resp=resp # type: ignore[arg-type]
- )
+ ) # fmt: skip
if next_was_not_called:
if middleware_resp is not None:
if self._framework_logger.level <= logging.DEBUG:
@@ -653,11 +657,13 @@ def _handle_unmatched_requests(self, req: BoltRequest, resp: BoltResponse) -> Bo
def use(self, *args) -> Optional[Callable]:
"""Registers a new global middleware to this app. This method can be used as either a decorator or a method.
- Refer to `App#middleware()` method's docstring for details."""
+ Refer to `App#middleware()` method's docstring for details.
+ """
return self.middleware(*args)
def middleware(self, *args) -> Optional[Callable]:
"""Registers a new middleware to this app.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -712,10 +718,10 @@ def step(
save: Optional[Union[Callable[..., Optional[BoltResponse]], Listener, Sequence[Callable]]] = None,
execute: Optional[Union[Callable[..., Optional[BoltResponse]], Listener, Sequence[Callable]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: register a new step from app listener.
+
+ Steps from apps for legacy workflows are now deprecated.
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new step from app listener.
@@ -857,6 +863,7 @@ def message(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new message event listener. This method can be used as either a decorator or a method.
+
Check the `App#event` method's docstring for details.
# Use this method as a decorator
@@ -919,6 +926,7 @@ def function(
ack_timeout: int = 3,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new Function listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -943,8 +951,12 @@ def reverse_string(ack: Ack, inputs: dict, complete: Complete, fail: Fail):
Only when all the matchers return True, the listener function can be invoked.
middleware: A list of lister middleware functions.
Only when all the middleware call `next()` method, the listener function can be invoked.
+ auto_acknowledge: Whether Bolt automatically acknowledges the function execution event on the
+ listener's behalf. When False, your listener must call `ack()` itself within `ack_timeout`
+ seconds (Default: True).
+ ack_timeout: The number of seconds to wait for the listener to call `ack()`.
+ Only takes effect when `auto_acknowledge` is False (Default: 3).
"""
-
if auto_acknowledge is True:
if ack_timeout != 3:
self._framework_logger.warning(warning_ack_timeout_has_no_effect(callback_id, ack_timeout))
@@ -969,6 +981,7 @@ def command(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new slash command listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1010,6 +1023,7 @@ def shortcut(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new shortcut listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1124,6 +1138,7 @@ def block_action(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `block_actions` action listener.
+
Refer to https://docs.slack.dev/reference/interaction-payloads/block_actions-payload/ for details.
"""
@@ -1141,7 +1156,9 @@ def attachment_action(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `interactive_message` action listener.
- Refer to https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1157,7 +1174,9 @@ def dialog_submission(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `dialog_submission` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1173,7 +1192,9 @@ def dialog_cancellation(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `dialog_cancellation` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1192,6 +1213,7 @@ def view(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `view_submission`/`view_closed` event listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1206,7 +1228,7 @@ def handle_submission(ack, body, client, view):
errors["block_c"] = "The value must be longer than 5 characters"
if len(errors) > 0:
ack(response_action="errors", errors=errors)
- return
+ return # Return early to display the validation errors to the user
# Acknowledge the view_submission event and close the modal
ack()
# Do whatever you want with the input data - here we're saving it to a DB
@@ -1240,6 +1262,7 @@ def view_submission(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `view_submission` listener.
+
Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_submission for
details.
"""
@@ -1258,7 +1281,9 @@ def view_closed(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `view_closed` listener.
- Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_closed for details."""
+
+ Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_closed for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1277,6 +1302,7 @@ def options(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new options listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1305,6 +1331,7 @@ def show_menu_options(ack):
To learn available arguments for middleware/listeners, see `slack_bolt.kwargs_injection.args`'s API document.
Args:
+ constraints: The conditions that match a request payload
matchers: A list of listener matcher functions.
Only when all the matchers return True, the listener function can be invoked.
middleware: A list of lister middleware functions.
@@ -1340,7 +1367,9 @@ def dialog_suggestion(
middleware: Optional[Sequence[Union[Callable, Middleware]]] = None,
) -> Callable[..., Optional[Callable[..., Optional[BoltResponse]]]]:
"""Registers a new `dialog_suggestion` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1469,7 +1498,7 @@ def __init__(
oauth_flow: Optional[OAuthFlow] = None,
http_server_logger_enabled: bool = True,
):
- """Slack App Development Server
+ """Slack App Development Server.
This is a thin wrapper of http.server.HTTPServer and is good enough
for your local development or prototyping.
diff --git a/slack_bolt/app/async_app.py b/slack_bolt/app/async_app.py
index cc94f9e15..729d626c2 100644
--- a/slack_bolt/app/async_app.py
+++ b/slack_bolt/app/async_app.py
@@ -213,6 +213,10 @@ async def message_hello(message, say): # async function
verification_token: Deprecated verification mechanism. This can be used only for ssl_check requests.
assistant_thread_context_store: Custom AssistantThreadContext store (Default: the built-in implementation,
which uses a parent message's metadata to store the latest context)
+ attaching_conversation_kwargs_enabled: False if you would like to disable the built-in
+ middleware (Default: True). `AttachingConversationKwargs` is a built-in middleware that attaches
+ conversation-specific listener arguments (such as `say`, `set_status`, `say_stream`, and
+ `set_suggested_prompts`) for assistant thread and direct message events.
"""
if signing_secret is None:
signing_secret = os.environ.get("SLACK_SIGNING_SECRET", "")
@@ -467,7 +471,7 @@ def _init_async_middleware_list(
@property
def name(self) -> str:
- """The name of this app (default: the filename)"""
+ """The name of this app (default: the filename)."""
return self._name
@property
@@ -511,6 +515,7 @@ def server(
host: Optional[str] = None,
) -> AsyncSlackAppServer:
"""Configure a web server using AIOHTTP.
+
Refer to https://docs.aiohttp.org/ for more details about AIOHTTP.
Args:
@@ -551,6 +556,7 @@ def app_factory():
def start(self, port: int = 3000, path: str = "/slack/events", host: Optional[str] = None) -> None:
"""Start a web server using AIOHTTP.
+
Refer to https://docs.aiohttp.org/ for more details about AIOHTTP.
Args:
@@ -588,7 +594,7 @@ async def async_middleware_next():
self._framework_logger.debug(f"Applying {middleware.name}")
resp = await middleware.async_process(
req=req, resp=resp, next=async_middleware_next # type: ignore[arg-type]
- )
+ ) # fmt: skip
if not middleware_state["next_called"]:
if resp is None:
# next() method was not called without providing the response to return to Slack
@@ -619,7 +625,7 @@ async def async_middleware_next():
# run all the middleware attached to this listener first
middleware_resp, next_was_not_called = await listener.run_async_middleware(
req=req, resp=resp # type: ignore[arg-type]
- )
+ ) # fmt: skip
if next_was_not_called:
if middleware_resp is not None:
if self._framework_logger.level <= logging.DEBUG:
@@ -687,6 +693,7 @@ def use(self, *args) -> Optional[Callable]:
def middleware(self, *args) -> Optional[Callable]:
"""Registers a new middleware to this app.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -736,10 +743,10 @@ def step(
save: Optional[Union[Callable[..., Optional[BoltResponse]], AsyncListener, Sequence[Callable]]] = None,
execute: Optional[Union[Callable[..., Optional[BoltResponse]], AsyncListener, Sequence[Callable]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: register a new step from app listener.
+
+ Steps from apps for legacy workflows are now deprecated.
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new step from app listener.
@@ -885,6 +892,7 @@ def message(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new message event listener. This method can be used as either a decorator or a method.
+
Check the `App#event` method's docstring for details.
# Use this method as a decorator
@@ -950,6 +958,7 @@ def function(
ack_timeout: int = 3,
) -> Callable[..., Optional[Callable[..., Awaitable[BoltResponse]]]]:
"""Registers a new Function listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -974,6 +983,11 @@ async def reverse_string(ack: AsyncAck, inputs: dict, complete: AsyncComplete, f
Only when all the matchers return True, the listener function can be invoked.
middleware: A list of lister middleware functions.
Only when all the middleware call `next()` method, the listener function can be invoked.
+ auto_acknowledge: Whether Bolt automatically acknowledges the function execution event on the
+ listener's behalf. When False, your listener must call `ack()` itself within `ack_timeout`
+ seconds (Default: True).
+ ack_timeout: The number of seconds to wait for the listener to call `ack()`.
+ Only takes effect when `auto_acknowledge` is False (Default: 3).
"""
if auto_acknowledge is True:
if ack_timeout != 3:
@@ -1001,6 +1015,7 @@ def command(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new slash command listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1042,6 +1057,7 @@ def shortcut(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new shortcut listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1156,6 +1172,7 @@ def block_action(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `block_actions` action listener.
+
Refer to https://docs.slack.dev/reference/interaction-payloads/block_actions-payload/ for details.
"""
@@ -1173,7 +1190,9 @@ def attachment_action(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `interactive_message` action listener.
- Refer to https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-messaging/legacy-message-buttons/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1189,7 +1208,9 @@ def dialog_submission(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `dialog_submission` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1204,8 +1225,10 @@ def dialog_cancellation(
matchers: Optional[Sequence[Callable[..., Awaitable[bool]]]] = None,
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
- """Registers a new `dialog_submission` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+ """Registers a new `dialog_cancellation` listener.
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1224,6 +1247,7 @@ def view(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `view_submission`/`view_closed` event listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1238,7 +1262,7 @@ async def handle_submission(ack, body, client, view):
errors["block_c"] = "The value must be longer than 5 characters"
if len(errors) > 0:
await ack(response_action="errors", errors=errors)
- return
+ return # Return early to display the validation errors to the user
# Acknowledge the view_submission event and close the modal
await ack()
# Do whatever you want with the input data - here we're saving it to a DB
@@ -1272,6 +1296,7 @@ def view_submission(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `view_submission` listener.
+
Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_submission for
details.
"""
@@ -1290,7 +1315,9 @@ def view_closed(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `view_closed` listener.
- Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_closed for details."""
+
+ Refer to https://docs.slack.dev/reference/interaction-payloads/view-interactions-payload/#view_closed for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
@@ -1309,6 +1336,7 @@ def options(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new options listener.
+
This method can be used as either a decorator or a method.
# Use this method as a decorator
@@ -1337,6 +1365,7 @@ async def show_menu_options(ack):
To learn available arguments for middleware/listeners, see `slack_bolt.kwargs_injection.async_args`'s API document.
Args:
+ constraints: The conditions that match a request payload
matchers: A list of listener matcher functions.
Only when all the matchers return True, the listener function can be invoked.
middleware: A list of lister middleware functions.
@@ -1372,7 +1401,9 @@ def dialog_suggestion(
middleware: Optional[Sequence[Union[Callable, AsyncMiddleware]]] = None,
) -> Callable[..., Optional[Callable[..., Awaitable[Optional[BoltResponse]]]]]:
"""Registers a new `dialog_suggestion` listener.
- Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details."""
+
+ Refer to https://docs.slack.dev/legacy/legacy-dialogs/ for details.
+ """
def __call__(*args, **kwargs):
functions = self._to_listener_functions(kwargs) if kwargs else list(args)
diff --git a/slack_bolt/app/async_server.py b/slack_bolt/app/async_server.py
index f21d35932..9511a5f7b 100644
--- a/slack_bolt/app/async_server.py
+++ b/slack_bolt/app/async_server.py
@@ -26,6 +26,7 @@ def __init__(
host: Optional[str] = None,
):
"""Standalone AIOHTTP Web Server.
+
Refer to https://docs.aiohttp.org/en/stable/web.html for details of AIOHTTP.
Args:
diff --git a/slack_bolt/async_app.py b/slack_bolt/async_app.py
index f95d952aa..f2e2fbfa8 100644
--- a/slack_bolt/async_app.py
+++ b/slack_bolt/async_app.py
@@ -1,4 +1,4 @@
-"""Module for creating asyncio based apps
+"""Module for creating asyncio based apps.
### Creating an async app
diff --git a/slack_bolt/authorization/__init__.py b/slack_bolt/authorization/__init__.py
index 4b80a93bb..da6fa4b98 100644
--- a/slack_bolt/authorization/__init__.py
+++ b/slack_bolt/authorization/__init__.py
@@ -1,5 +1,4 @@
-"""Authorization is the process of determining which Slack credentials should be available
-while processing an incoming Slack event.
+"""Authorization determines which Slack credentials should be available while processing an incoming Slack event.
Refer to https://docs.slack.dev/tools/bolt-python/concepts/authorization for details.
"""
diff --git a/slack_bolt/authorization/async_authorize.py b/slack_bolt/authorization/async_authorize.py
index f3303e429..aa61a209d 100644
--- a/slack_bolt/authorization/async_authorize.py
+++ b/slack_bolt/authorization/async_authorize.py
@@ -17,8 +17,7 @@
class AsyncAuthorize:
- """This provides authorize function that returns AuthorizeResult
- for an incoming request from Slack."""
+ """This provides authorize function that returns AuthorizeResult for an incoming request from Slack."""
def __init__(self):
pass
@@ -39,9 +38,7 @@ async def __call__(
class AsyncCallableAuthorize(AsyncAuthorize):
- """When you pass the authorize argument in AsyncApp constructor,
- This authorize implementation will be used.
- """
+ """When you pass the `authorize` argument in AsyncApp constructor, this `authorize` implementation will be used."""
def __init__(self, *, logger: Logger, func: Callable[..., Awaitable[AuthorizeResult]]):
self.logger = logger
@@ -107,6 +104,7 @@ async def __call__(
class AsyncInstallationStoreAuthorize(AsyncAuthorize):
"""If you use the OAuth flow settings, this authorize implementation will be used.
+
As long as your own InstallationStore (or the built-in ones) works as you expect,
you can expect that the authorize layer should work for you without any customization.
"""
@@ -356,7 +354,7 @@ async def __call__(
# ------------------------------------------------
def _debug_log_for_not_found(self, enterprise_id: Optional[str], team_id: Optional[str]):
- self.logger.debug("No installation data found " f"for enterprise_id: {enterprise_id} team_id: {team_id}")
+ self.logger.debug(f"No installation data found for enterprise_id: {enterprise_id} team_id: {team_id}")
async def _rotate_and_save_tokens_if_necessary(self, installation: Optional[Installation]) -> Optional[Installation]:
if installation is None or (installation.user_refresh_token is None and installation.bot_refresh_token is None):
diff --git a/slack_bolt/authorization/authorize.py b/slack_bolt/authorization/authorize.py
index afed6fa8b..bcd19af72 100644
--- a/slack_bolt/authorization/authorize.py
+++ b/slack_bolt/authorization/authorize.py
@@ -16,8 +16,7 @@
class Authorize:
- """This provides authorize function that returns AuthorizeResult
- for an incoming request from Slack."""
+ """This provides authorize function that returns AuthorizeResult for an incoming request from Slack."""
def __init__(self):
pass
@@ -38,9 +37,7 @@ def __call__(
class CallableAuthorize(Authorize):
- """When you pass the `authorize` argument in AsyncApp constructor,
- This `authorize` implementation will be used.
- """
+ """When you pass the `authorize` argument in App constructor, this `authorize` implementation will be used."""
def __init__(
self,
@@ -111,6 +108,7 @@ def __call__(
class InstallationStoreAuthorize(Authorize):
"""If you use the OAuth flow settings, this `authorize` implementation will be used.
+
As long as your own InstallationStore (or the built-in ones) works as you expect,
you can expect that the `authorize` layer should work for you without any customization.
"""
@@ -353,7 +351,7 @@ def __call__(
# ------------------------------------------------
def _debug_log_for_not_found(self, enterprise_id: Optional[str], team_id: Optional[str]):
- self.logger.debug("No installation data found " f"for enterprise_id: {enterprise_id} team_id: {team_id}")
+ self.logger.debug(f"No installation data found for enterprise_id: {enterprise_id} team_id: {team_id}")
def _rotate_and_save_tokens_if_necessary(self, installation: Optional[Installation]) -> Optional[Installation]:
if installation is None or (installation.user_refresh_token is None and installation.bot_refresh_token is None):
diff --git a/slack_bolt/authorization/authorize_result.py b/slack_bolt/authorization/authorize_result.py
index cbf1a4678..4a7b0e656 100644
--- a/slack_bolt/authorization/authorize_result.py
+++ b/slack_bolt/authorization/authorize_result.py
@@ -4,7 +4,7 @@
class AuthorizeResult(dict):
- """Authorize function call result"""
+ """Authorize function call result."""
enterprise_id: Optional[str]
team_id: Optional[str]
@@ -39,7 +39,8 @@ def __init__(
user_token: Optional[str] = None,
user_scopes: Optional[Union[Sequence[str], str]] = None,
):
- """
+ """Initialize the authorize function call result.
+
Args:
enterprise_id: Organization ID (Enterprise Grid) starting with `E`
team_id: Workspace ID starting with `T`
@@ -52,7 +53,7 @@ def __init__(
user_id: The request user ID
user: The request user's name
user_token: User access token starting with `xoxp-`
- user_scopes: The scopes associated wth the user token
+ user_scopes: The scopes associated with the user token
"""
self["enterprise_id"] = self.enterprise_id = enterprise_id
self["team_id"] = self.team_id = team_id
diff --git a/slack_bolt/context/__init__.py b/slack_bolt/context/__init__.py
index 865825601..5d157e42a 100644
--- a/slack_bolt/context/__init__.py
+++ b/slack_bolt/context/__init__.py
@@ -1,4 +1,5 @@
"""All listeners have access to a context dictionary, which can be used to enrich events with additional information.
+
Bolt automatically attaches information that is included in the incoming event,
like `user_id`, `team_id`, `channel_id`, and `enterprise_id`.
diff --git a/slack_bolt/context/assistant/assistant_utilities.py b/slack_bolt/context/assistant/assistant_utilities.py
index 42f05c94b..e9614fd8d 100644
--- a/slack_bolt/context/assistant/assistant_utilities.py
+++ b/slack_bolt/context/assistant/assistant_utilities.py
@@ -1,4 +1,3 @@
-import warnings
from typing import Optional
from slack_sdk.web import WebClient
@@ -11,8 +10,6 @@
from .internals import has_channel_id_and_thread_ts
from ..get_thread_context.get_thread_context import GetThreadContext
from ..save_thread_context import SaveThreadContext
-from ..set_status import SetStatus
-from ..set_suggested_prompts import SetSuggestedPrompts
from ..set_title import SetTitle
@@ -47,28 +44,10 @@ def __init__(
# When moving this code to Bolt internals, no need to raise an exception for this pattern
raise ValueError(f"Cannot instantiate Assistant for this event pattern ({self.payload})")
- def is_valid(self) -> bool:
- return self.channel_id is not None and self.thread_ts is not None
-
- @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
def set_title(self) -> SetTitle:
return SetTitle(self.client, self.channel_id, self.thread_ts)
- @property
- def set_suggested_prompts(self) -> SetSuggestedPrompts:
- return SetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
-
@property
def say(self) -> Say:
def build_metadata() -> Optional[dict]:
diff --git a/slack_bolt/context/assistant/async_assistant_utilities.py b/slack_bolt/context/assistant/async_assistant_utilities.py
index b40b2619c..6acf531ce 100644
--- a/slack_bolt/context/assistant/async_assistant_utilities.py
+++ b/slack_bolt/context/assistant/async_assistant_utilities.py
@@ -1,4 +1,3 @@
-import warnings
from typing import Optional
from slack_sdk.web.async_client import AsyncWebClient
@@ -14,8 +13,6 @@
from .internals import has_channel_id_and_thread_ts
from ..get_thread_context.async_get_thread_context import AsyncGetThreadContext
from ..save_thread_context.async_save_thread_context import AsyncSaveThreadContext
-from ..set_status.async_set_status import AsyncSetStatus
-from ..set_suggested_prompts.async_set_suggested_prompts import AsyncSetSuggestedPrompts
from ..set_title.async_set_title import AsyncSetTitle
@@ -50,28 +47,10 @@ def __init__(
# When moving this code to Bolt internals, no need to raise an exception for this pattern
raise ValueError(f"Cannot instantiate Assistant for this event pattern ({self.payload})")
- def is_valid(self) -> bool:
- return self.channel_id is not None and self.thread_ts is not None
-
- @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
def set_title(self) -> AsyncSetTitle:
return AsyncSetTitle(self.client, self.channel_id, self.thread_ts)
- @property
- def set_suggested_prompts(self) -> AsyncSetSuggestedPrompts:
- return AsyncSetSuggestedPrompts(self.client, self.channel_id, self.thread_ts)
-
@property
def say(self) -> AsyncSay:
return AsyncSay(
diff --git a/slack_bolt/context/assistant/internals.py b/slack_bolt/context/assistant/internals.py
index ee449c31b..15fc55d80 100644
--- a/slack_bolt/context/assistant/internals.py
+++ b/slack_bolt/context/assistant/internals.py
@@ -1,5 +1,6 @@
def has_channel_id_and_thread_ts(payload: dict) -> bool:
"""Verifies if the given payload has both channel_id and thread_ts under assistant_thread property.
+
This data pattern is available for assistant_* events.
"""
return (
diff --git a/slack_bolt/context/assistant/thread_context_store/file/__init__.py b/slack_bolt/context/assistant/thread_context_store/file/__init__.py
index a29f3b2c0..3590e6709 100644
--- a/slack_bolt/context/assistant/thread_context_store/file/__init__.py
+++ b/slack_bolt/context/assistant/thread_context_store/file/__init__.py
@@ -6,7 +6,6 @@
class FileAssistantThreadContextStore(AssistantThreadContextStore):
-
def __init__(
self,
base_dir: str = str(Path.home()) + "/.bolt-app-assistant-thread-contexts",
diff --git a/slack_bolt/context/async_context.py b/slack_bolt/context/async_context.py
index 94b2b5cbe..19577db97 100644
--- a/slack_bolt/context/async_context.py
+++ b/slack_bolt/context/async_context.py
@@ -145,7 +145,9 @@ async def handle_button_clicks(ack, respond):
@property
def complete(self) -> AsyncComplete:
- """`complete()` function for this request. Once a custom function's state is set to complete,
+ """`complete()` function for this request.
+
+ Once a custom function's state is set to complete,
any outputs the function returns will be passed along to the next step of its housing workflow,
or complete the workflow if the function is the last step in a workflow. Additionally,
any interactivity handlers associated to a function invocation will no longer be invocable.
@@ -169,7 +171,9 @@ async def handle_button_clicks(context):
@property
def fail(self) -> AsyncFail:
- """`fail()` function for this request. Once a custom function's state is set to error,
+ """`fail()` function for this request.
+
+ Once a custom function's state is set to error,
its housing workflow will be interrupted and any provided error message will be passed
on to the end user through SlackBot. Additionally, any interactivity handlers associated
to a function invocation will no longer be invocable.
diff --git a/slack_bolt/context/base_context.py b/slack_bolt/context/base_context.py
index 502febcb8..c9800aede 100644
--- a/slack_bolt/context/base_context.py
+++ b/slack_bolt/context/base_context.py
@@ -85,6 +85,7 @@ def user_id(self) -> Optional[str]:
@property
def actor_enterprise_id(self) -> Optional[str]:
"""The action's actor's Enterprise Grid organization ID.
+
Note that this property is especially useful for handling events in Slack Connect channels.
That being said, it's not guaranteed to have a valid ID for all events due to server-side inconsistency.
"""
@@ -93,6 +94,7 @@ def actor_enterprise_id(self) -> Optional[str]:
@property
def actor_team_id(self) -> Optional[str]:
"""The action's actor's workspace ID.
+
Note that this property is especially useful for handling events in Slack Connect channels.
That being said, it's not guaranteed to have a valid ID for all events due to server-side inconsistency.
"""
@@ -101,6 +103,7 @@ def actor_team_id(self) -> Optional[str]:
@property
def actor_user_id(self) -> Optional[str]:
"""The action's actor's user ID.
+
Note that this property is especially useful for handling events in Slack Connect channels.
That being said, it's not guaranteed to have a valid ID for all events due to server-side inconsistency.
"""
@@ -123,12 +126,13 @@ def response_url(self) -> Optional[str]:
@property
def matches(self) -> Optional[Tuple]:
- """Returns all the matched parts in message listener's regexp"""
+ """Returns all the matched parts in message listener's regexp."""
return self.get("matches")
@property
def function_execution_id(self) -> Optional[str]:
"""The `function_execution_id` associated with this request.
+
Only available for `function_executed` and interactivity events scoped to a custom step.
"""
return self.get("function_execution_id")
@@ -136,6 +140,7 @@ def function_execution_id(self) -> Optional[str]:
@property
def inputs(self) -> Optional[Dict[str, Any]]:
"""The `inputs` associated with this request.
+
Only available for `function_executed` and interactivity events scoped to a custom step.
"""
return self.get("inputs")
@@ -150,6 +155,7 @@ def authorize_result(self) -> Optional[AuthorizeResult]:
@property
def function_bot_access_token(self) -> Optional[str]:
"""The bot token resolved for this function request.
+
Only available for `function_executed` and interactivity events scoped to a custom step.
"""
return self.get("function_bot_access_token")
diff --git a/slack_bolt/context/context.py b/slack_bolt/context/context.py
index b101460a5..661e9cc94 100644
--- a/slack_bolt/context/context.py
+++ b/slack_bolt/context/context.py
@@ -146,7 +146,9 @@ def handle_button_clicks(ack, respond):
@property
def complete(self) -> Complete:
- """`complete()` function for this request. Once a custom function's state is set to complete,
+ """`complete()` function for this request.
+
+ Once a custom function's state is set to complete,
any outputs the function returns will be passed along to the next step of its housing workflow,
or complete the workflow if the function is the last step in a workflow. Additionally,
any interactivity handlers associated to a function invocation will no longer be invocable.
@@ -170,7 +172,9 @@ def handle_button_clicks(context):
@property
def fail(self) -> Fail:
- """`fail()` function for this request. Once a custom function's state is set to error,
+ """`fail()` function for this request.
+
+ Once a custom function's state is set to error,
its housing workflow will be interrupted and any provided error message will be passed
on to the end user through SlackBot. Additionally, any interactivity handlers associated
to a function invocation will no longer be invocable.
diff --git a/slack_bolt/context/say_stream/async_say_stream.py b/slack_bolt/context/say_stream/async_say_stream.py
index af776891b..df9b362e2 100644
--- a/slack_bolt/context/say_stream/async_say_stream.py
+++ b/slack_bolt/context/say_stream/async_say_stream.py
@@ -34,6 +34,9 @@ async def __call__(
recipient_team_id: Optional[str] = None,
recipient_user_id: Optional[str] = None,
thread_ts: Optional[str] = None,
+ icon_emoji: Optional[str] = None,
+ icon_url: Optional[str] = None,
+ username: Optional[str] = None,
**kwargs,
) -> AsyncChatStream:
"""Starts a new chat stream with context."""
@@ -51,6 +54,9 @@ async def __call__(
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,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
return await self.client.chat_stream(
@@ -58,5 +64,8 @@ async def __call__(
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,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
diff --git a/slack_bolt/context/say_stream/say_stream.py b/slack_bolt/context/say_stream/say_stream.py
index b6a5ca797..15bdcc110 100644
--- a/slack_bolt/context/say_stream/say_stream.py
+++ b/slack_bolt/context/say_stream/say_stream.py
@@ -34,6 +34,9 @@ def __call__(
recipient_team_id: Optional[str] = None,
recipient_user_id: Optional[str] = None,
thread_ts: Optional[str] = None,
+ icon_emoji: Optional[str] = None,
+ icon_url: Optional[str] = None,
+ username: Optional[str] = None,
**kwargs,
) -> ChatStream:
"""Starts a new chat stream with context."""
@@ -51,6 +54,9 @@ def __call__(
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,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
return self.client.chat_stream(
@@ -58,5 +64,8 @@ def __call__(
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,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
diff --git a/slack_bolt/context/set_status/async_set_status.py b/slack_bolt/context/set_status/async_set_status.py
index e2c451f46..f10cc195c 100644
--- a/slack_bolt/context/set_status/async_set_status.py
+++ b/slack_bolt/context/set_status/async_set_status.py
@@ -23,6 +23,9 @@ async def __call__(
self,
status: str,
loading_messages: Optional[List[str]] = None,
+ icon_emoji: Optional[str] = None,
+ icon_url: Optional[str] = None,
+ username: Optional[str] = None,
**kwargs,
) -> AsyncSlackResponse:
return await self.client.assistant_threads_setStatus(
@@ -30,5 +33,8 @@ async def __call__(
thread_ts=self.thread_ts,
status=status,
loading_messages=loading_messages,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
diff --git a/slack_bolt/context/set_status/set_status.py b/slack_bolt/context/set_status/set_status.py
index 0ed612e16..055a5cab7 100644
--- a/slack_bolt/context/set_status/set_status.py
+++ b/slack_bolt/context/set_status/set_status.py
@@ -23,6 +23,9 @@ def __call__(
self,
status: str,
loading_messages: Optional[List[str]] = None,
+ icon_emoji: Optional[str] = None,
+ icon_url: Optional[str] = None,
+ username: Optional[str] = None,
**kwargs,
) -> SlackResponse:
return self.client.assistant_threads_setStatus(
@@ -30,5 +33,8 @@ def __call__(
thread_ts=self.thread_ts,
status=status,
loading_messages=loading_messages,
+ icon_emoji=icon_emoji,
+ icon_url=icon_url,
+ username=username,
**kwargs,
)
diff --git a/slack_bolt/context/set_suggested_prompts/async_set_suggested_prompts.py b/slack_bolt/context/set_suggested_prompts/async_set_suggested_prompts.py
index 2079b6448..68b41858b 100644
--- a/slack_bolt/context/set_suggested_prompts/async_set_suggested_prompts.py
+++ b/slack_bolt/context/set_suggested_prompts/async_set_suggested_prompts.py
@@ -7,13 +7,13 @@
class AsyncSetSuggestedPrompts:
client: AsyncWebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: AsyncWebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -23,6 +23,7 @@ async def __call__(
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> AsyncSlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -33,7 +34,7 @@ async def __call__(
return await self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
diff --git a/slack_bolt/context/set_suggested_prompts/set_suggested_prompts.py b/slack_bolt/context/set_suggested_prompts/set_suggested_prompts.py
index 21ff815e1..349481df4 100644
--- a/slack_bolt/context/set_suggested_prompts/set_suggested_prompts.py
+++ b/slack_bolt/context/set_suggested_prompts/set_suggested_prompts.py
@@ -7,13 +7,13 @@
class SetSuggestedPrompts:
client: WebClient
channel_id: str
- thread_ts: str
+ thread_ts: Optional[str]
def __init__(
self,
client: WebClient,
channel_id: str,
- thread_ts: str,
+ thread_ts: Optional[str] = None,
):
self.client = client
self.channel_id = channel_id
@@ -23,6 +23,7 @@ def __call__(
self,
prompts: Sequence[Union[str, Dict[str, str]]],
title: Optional[str] = None,
+ thread_ts: Optional[str] = None,
) -> SlackResponse:
prompts_arg: List[Dict[str, str]] = []
for prompt in prompts:
@@ -33,7 +34,7 @@ def __call__(
return self.client.assistant_threads_setSuggestedPrompts(
channel_id=self.channel_id,
- thread_ts=self.thread_ts,
+ thread_ts=thread_ts if thread_ts is not None else self.thread_ts,
prompts=prompts_arg,
title=title,
)
diff --git a/slack_bolt/error/__init__.py b/slack_bolt/error/__init__.py
index 19716cd74..baa31565c 100644
--- a/slack_bolt/error/__init__.py
+++ b/slack_bolt/error/__init__.py
@@ -4,7 +4,7 @@
class BoltError(Exception):
- """General class in a Bolt app"""
+ """General class in a Bolt app."""
class BoltUnhandledRequestError(BoltError):
diff --git a/slack_bolt/kwargs_injection/args.py b/slack_bolt/kwargs_injection/args.py
index f2b4099d6..1c215743d 100644
--- a/slack_bolt/kwargs_injection/args.py
+++ b/slack_bolt/kwargs_injection/args.py
@@ -21,6 +21,7 @@
class Args:
"""All the arguments in this class are available in any middleware / listeners.
+
You can inject the named variables in the argument list in arbitrary order.
@app.action("link_button")
diff --git a/slack_bolt/kwargs_injection/async_args.py b/slack_bolt/kwargs_injection/async_args.py
index 2217cfe9f..3c1806b06 100644
--- a/slack_bolt/kwargs_injection/async_args.py
+++ b/slack_bolt/kwargs_injection/async_args.py
@@ -20,6 +20,7 @@
class AsyncArgs:
"""All the arguments in this class are available in any middleware / listeners.
+
You can inject the named variables in the argument list in arbitrary order.
@app.action("link_button")
diff --git a/slack_bolt/listener/__init__.py b/slack_bolt/listener/__init__.py
index a12a2b821..6b501ddae 100644
--- a/slack_bolt/listener/__init__.py
+++ b/slack_bolt/listener/__init__.py
@@ -1,6 +1,7 @@
-"""Listeners process an incoming request from Slack if the request's type or data structure matches
-the predefined conditions of the listener. Typically, a listener acknowledge requests from Slack,
-process the request data, and may send response back to Slack.
+"""Listeners process incoming requests from Slack.
+
+A listener runs when the request's type or data structure matches its predefined conditions.
+Typically, a listener acknowledges the request, processes its data, and may send a response back to Slack.
"""
# Don't add async module imports here
diff --git a/slack_bolt/listener/async_builtins.py b/slack_bolt/listener/async_builtins.py
index 7b3bc4da7..5c9711c24 100644
--- a/slack_bolt/listener/async_builtins.py
+++ b/slack_bolt/listener/async_builtins.py
@@ -5,7 +5,7 @@
class AsyncTokenRevocationListeners:
- """Listener functions to handle token revocation / uninstallation events"""
+ """Listener functions to handle token revocation / uninstallation events."""
installation_store: AsyncInstallationStore
diff --git a/slack_bolt/listener/async_listener_completion_handler.py b/slack_bolt/listener/async_listener_completion_handler.py
index 9fc002a91..2cd7bc41a 100644
--- a/slack_bolt/listener/async_listener_completion_handler.py
+++ b/slack_bolt/listener/async_listener_completion_handler.py
@@ -15,7 +15,7 @@ async def handle(
request: AsyncBoltRequest,
response: Optional[BoltResponse],
) -> None:
- """Do something extra after the listener execution
+ """Do something extra after the listener execution.
Args:
request: The request.
diff --git a/slack_bolt/listener/async_listener_start_handler.py b/slack_bolt/listener/async_listener_start_handler.py
index b7b10e9e7..d244fe968 100644
--- a/slack_bolt/listener/async_listener_start_handler.py
+++ b/slack_bolt/listener/async_listener_start_handler.py
@@ -15,7 +15,7 @@ async def handle(
request: AsyncBoltRequest,
response: Optional[BoltResponse],
) -> None:
- """Do something extra before the listener execution
+ """Do something extra before the listener execution.
Args:
request: The request.
diff --git a/slack_bolt/listener/builtins.py b/slack_bolt/listener/builtins.py
index ee5891f27..e6ff7b37d 100644
--- a/slack_bolt/listener/builtins.py
+++ b/slack_bolt/listener/builtins.py
@@ -3,7 +3,7 @@
class TokenRevocationListeners:
- """Listener functions to handle token revocation / uninstallation events"""
+ """Listener functions to handle token revocation / uninstallation events."""
installation_store: InstallationStore
diff --git a/slack_bolt/listener/listener_completion_handler.py b/slack_bolt/listener/listener_completion_handler.py
index b2c08a205..454ee52d0 100644
--- a/slack_bolt/listener/listener_completion_handler.py
+++ b/slack_bolt/listener/listener_completion_handler.py
@@ -15,7 +15,7 @@ def handle(
request: BoltRequest,
response: Optional[BoltResponse],
) -> None:
- """Do something extra after the listener execution
+ """Do something extra after the listener execution.
Args:
request: The request.
diff --git a/slack_bolt/listener_matcher/__init__.py b/slack_bolt/listener_matcher/__init__.py
index 26f164ba6..85c89c7bc 100644
--- a/slack_bolt/listener_matcher/__init__.py
+++ b/slack_bolt/listener_matcher/__init__.py
@@ -1,4 +1,5 @@
"""A listener matcher is a simplified version of listener middleware.
+
A listener matcher function returns bool value instead of `next()` method invocation inside.
This interface enables developers to utilize simple predicate functions for additional listener conditions.
"""
diff --git a/slack_bolt/logger/messages.py b/slack_bolt/logger/messages.py
index 80e68d022..8c7439683 100644
--- a/slack_bolt/logger/messages.py
+++ b/slack_bolt/logger/messages.py
@@ -45,7 +45,7 @@ def error_auth_test_failure(error_response: SlackResponse) -> str:
def error_token_required() -> str:
- return "Either an env variable `SLACK_BOT_TOKEN` " "or `token` argument in the constructor is required."
+ return "Either an env variable `SLACK_BOT_TOKEN` or `token` argument in the constructor is required."
def error_unexpected_listener_middleware(middleware_type) -> str:
@@ -89,9 +89,7 @@ def warning_client_prioritized_and_token_skipped() -> str:
def warning_token_skipped() -> str:
- return (
- "As `installation_store` or `authorize` has been used, " "`token` (or SLACK_BOT_TOKEN env variable) will be ignored."
- )
+ return "As `installation_store` or `authorize` has been used, `token` (or SLACK_BOT_TOKEN env variable) will be ignored."
def warning_installation_store_conflicts() -> str:
@@ -99,7 +97,8 @@ def warning_installation_store_conflicts() -> str:
def warning_unhandled_by_global_middleware(
- name: str, req: Union[BoltRequest, "AsyncBoltRequest"] # type: ignore[name-defined]
+ name: str,
+ req: Union[BoltRequest, "AsyncBoltRequest"], # type: ignore[name-defined]
) -> str:
return (
f"A global middleware ({name}) skipped calling either `next()` or `next_()` "
@@ -194,8 +193,8 @@ def warning_unhandled_request(
return _build_unhandled_request_suggestion(
default_message,
f"""
-from slack_bolt.workflows.step{'.async_step' if is_async else ''} import {'Async' if is_async else ''}WorkflowStep
-ws = {'Async' if is_async else ''}WorkflowStep(
+from slack_bolt.workflows.step{".async_step" if is_async else ""} import {"Async" if is_async else ""}WorkflowStep
+ws = {"Async" if is_async else ""}WorkflowStep(
callback_id="{callback_id}",
edit=edit,
save=save,
@@ -214,8 +213,8 @@ def warning_unhandled_request(
default_message,
f"""
@app.action("{action_id_or_callback_id}")
-{'async ' if is_async else ''}def handle_some_action(ack, body, logger):
- {'await ' if is_async else ''}ack()
+{"async " if is_async else ""}def handle_some_action(ack, body, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
""",
)
@@ -225,13 +224,13 @@ def warning_unhandled_request(
if req.body.get("action_id") is not None:
constraints = '"' + req.body["action_id"] + '"'
elif req.body.get("type") == "dialog_suggestion":
- constraints = f"""{{"type": "dialog_suggestion", "callback_id": "{req.body.get('callback_id')}"}}"""
+ constraints = f"""{{"type": "dialog_suggestion", "callback_id": "{req.body.get("callback_id")}"}}"""
return _build_unhandled_request_suggestion(
default_message,
f"""
@app.options({constraints})
-{'async ' if is_async else ''}def handle_some_options(ack):
- {'await ' if is_async else ''}ack(options=[ ... ])
+{"async " if is_async else ""}def handle_some_options(ack):
+ {"await " if is_async else ""}ack(options=[ ... ])
""",
)
if is_shortcut(req.body):
@@ -241,8 +240,8 @@ def warning_unhandled_request(
default_message,
f"""
@app.shortcut("{id}")
-{'async ' if is_async else ''}def handle_shortcuts(ack, body, logger):
- {'await ' if is_async else ''}ack()
+{"async " if is_async else ""}def handle_shortcuts(ack, body, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
""",
)
@@ -251,9 +250,9 @@ def warning_unhandled_request(
return _build_unhandled_request_suggestion(
default_message,
f"""
-@app.view("{req.body.get('view', {}).get('callback_id', 'modal-view-id')}")
-{'async ' if is_async else ''}def handle_view_submission_events(ack, body, logger):
- {'await ' if is_async else ''}ack()
+@app.view("{req.body.get("view", {}).get("callback_id", "modal-view-id")}")
+{"async " if is_async else ""}def handle_view_submission_events(ack, body, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
""",
)
@@ -262,9 +261,9 @@ def warning_unhandled_request(
return _build_unhandled_request_suggestion(
default_message,
f"""
-@app.view_closed("{req.body.get('view', {}).get('callback_id', 'modal-view-id')}")
-{'async ' if is_async else ''}def handle_view_closed_events(ack, body, logger):
- {'await ' if is_async else ''}ack()
+@app.view_closed("{req.body.get("view", {}).get("callback_id", "modal-view-id")}")
+{"async " if is_async else ""}def handle_view_closed_events(ack, body, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
""",
)
@@ -279,23 +278,23 @@ def warning_unhandled_request(
default_message,
f"""
@app.function("{callback_id}")
-{'async ' if is_async else ''}def handle_some_function(ack, body, complete, fail, logger):
- {'await ' if is_async else ''}ack()
+{"async " if is_async else ""}def handle_some_function(ack, body, complete, fail, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
try:
# TODO: do something here
outputs = {{}}
- {'await ' if is_async else ''}complete(outputs=outputs)
+ {"await " if is_async else ""}complete(outputs=outputs)
except Exception as e:
error = f"Failed to handle a function request (error: {{e}})"
- {'await ' if is_async else ''}fail(error=error)
+ {"await " if is_async else ""}fail(error=error)
""",
)
return _build_unhandled_request_suggestion(
default_message,
f"""
@app.event("{event_type}")
-{'async ' if is_async else ''}def handle_{event_type}_events(body, logger):
+{"async " if is_async else ""}def handle_{event_type}_events(body, logger):
logger.info(body)
""",
)
@@ -306,8 +305,8 @@ def warning_unhandled_request(
default_message,
f"""
@app.command("{command}")
-{'async ' if is_async else ''}def handle_some_command(ack, body, logger):
- {'await ' if is_async else ''}ack()
+{"async " if is_async else ""}def handle_some_command(ack, body, logger):
+ {"await " if is_async else ""}ack()
logger.info(body)
""",
)
@@ -320,8 +319,7 @@ def warning_did_not_call_ack(listener_name: str) -> str:
def warning_bot_only_conflicts() -> str:
return (
- "installation_store_bot_only exists in both App and OAuthFlow.settings. "
- "The one passed in App constructor is used."
+ "installation_store_bot_only exists in both App and OAuthFlow.settings. The one passed in App constructor is used."
)
@@ -334,7 +332,7 @@ def warning_skip_uncommon_arg_name(arg_name: str) -> str:
def warning_ack_timeout_has_no_effect(identifier: Union[str, Pattern], ack_timeout: int) -> str:
handler_example = f'@app.function("{identifier}")' if isinstance(identifier, str) else f"@app.function({identifier})"
- return f"On {handler_example}, as `auto_acknowledge` is `True`, " f"`ack_timeout={ack_timeout}` you gave will be unused"
+ return f"On {handler_example}, as `auto_acknowledge` is `True`, `ack_timeout={ack_timeout}` you gave will be unused"
# -------------------------------
diff --git a/slack_bolt/middleware/__init__.py b/slack_bolt/middleware/__init__.py
index c28ffd78d..c62cd6650 100644
--- a/slack_bolt/middleware/__init__.py
+++ b/slack_bolt/middleware/__init__.py
@@ -1,5 +1,6 @@
-"""A middleware processes request data and calls `next()` method
-if the execution chain should continue running the following middleware.
+"""A middleware processes request data and controls the execution chain.
+
+Call the `next()` method if the execution chain should continue running the following middleware.
Middleware can be used globally before all listener executions.
It's also possible to run a middleware only for a particular listener.
diff --git a/slack_bolt/middleware/assistant/assistant.py b/slack_bolt/middleware/assistant/assistant.py
index ad842f94d..98347d012 100644
--- a/slack_bolt/middleware/assistant/assistant.py
+++ b/slack_bolt/middleware/assistant/assistant.py
@@ -213,9 +213,7 @@ def _merge_matchers(
primary_matcher: Callable[..., bool],
custom_matchers: Optional[Union[Callable[..., bool], ListenerMatcher]],
):
- return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + (
- custom_matchers or []
- ) # type: ignore[operator]
+ return [CustomListenerMatcher(app_name=self.app_name, func=primary_matcher)] + (custom_matchers or []) # type: ignore[operator]
@staticmethod
def default_thread_context_changed(save_thread_context: SaveThreadContext, payload: dict):
diff --git a/slack_bolt/middleware/async_middleware.py b/slack_bolt/middleware/async_middleware.py
index 163def40a..0283bb3e8 100644
--- a/slack_bolt/middleware/async_middleware.py
+++ b/slack_bolt/middleware/async_middleware.py
@@ -20,6 +20,7 @@ async def async_process(
next: Callable[[], Awaitable[BoltResponse]],
) -> Optional[BoltResponse]:
"""Processes a request data before other middleware and listeners.
+
A middleware calls `next()` function if the chain should continue.
@app.middleware
@@ -47,5 +48,5 @@ async def simple_middleware(req, resp, next_):
@property
def name(self) -> str:
- """The name of this middleware"""
+ """The name of this middleware."""
return f"{self.__module__}.{self.__class__.__name__}"
diff --git a/slack_bolt/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.py b/slack_bolt/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.py
index 315ec2a50..d9069e922 100644
--- a/slack_bolt/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.py
+++ b/slack_bolt/middleware/attaching_conversation_kwargs/async_attaching_conversation_kwargs.py
@@ -4,14 +4,21 @@
from slack_bolt.context.assistant.thread_context_store.async_store import AsyncAssistantThreadContextStore
from slack_bolt.context.say_stream.async_say_stream import AsyncSayStream
from slack_bolt.context.set_status.async_set_status import AsyncSetStatus
+from slack_bolt.context.set_suggested_prompts.async_set_suggested_prompts import AsyncSetSuggestedPrompts
from slack_bolt.middleware.async_middleware import AsyncMiddleware
from slack_bolt.request.async_request import AsyncBoltRequest
-from slack_bolt.request.payload_utils import is_assistant_event, to_event
+from slack_bolt.request.payload_utils import (
+ is_app_home_opened_event,
+ is_assistant_event,
+ is_assistant_thread_context_changed_event,
+ is_assistant_thread_started_event,
+ is_im_message_event,
+ to_event,
+)
from slack_bolt.response import BoltResponse
class AsyncAttachingConversationKwargs(AsyncMiddleware):
-
thread_context_store: Optional[AsyncAssistantThreadContextStore]
def __init__(self, thread_context_store: Optional[AsyncAssistantThreadContextStore] = None):
@@ -25,32 +32,48 @@ async def async_process(
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,
- )
+ if event is None:
+ return await next()
+ if req.context.channel_id is None:
+ return await next()
+
+ if is_assistant_event(req.body):
+ # TODO: eventually we might remove this assistant specific logic
+ 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["get_thread_context"] = assistant.get_thread_context
+ req.context["save_thread_context"] = assistant.save_thread_context
+
+ if (
+ is_im_message_event(req.body)
+ or is_assistant_thread_started_event(req.body)
+ or is_assistant_thread_context_changed_event(req.body)
+ or is_app_home_opened_event(req.body, tab="messages")
+ ):
+ req.context["set_suggested_prompts"] = AsyncSetSuggestedPrompts(
+ client=req.context.client,
+ channel_id=req.context.channel_id,
+ thread_ts=req.context.thread_ts,
+ )
+
+ # TODO: in the future we might want to introduce a "proper" extract_ts utility
+ thread_ts_or_ts = req.context.thread_ts or event.get("ts")
+ if thread_ts_or_ts:
+ req.context["set_status"] = AsyncSetStatus(
+ client=req.context.client,
+ channel_id=req.context.channel_id,
+ thread_ts=thread_ts_or_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_or_ts,
+ )
return await next()
diff --git a/slack_bolt/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.py b/slack_bolt/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.py
index 33847fd56..9ff1c0bdd 100644
--- a/slack_bolt/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.py
+++ b/slack_bolt/middleware/attaching_conversation_kwargs/attaching_conversation_kwargs.py
@@ -1,17 +1,24 @@
from typing import Optional, Callable
-from slack_bolt.context.assistant.assistant_utilities import AssistantUtilities
from slack_bolt.context.assistant.thread_context_store.store import AssistantThreadContextStore
from slack_bolt.context.say_stream.say_stream import SayStream
from slack_bolt.context.set_status.set_status import SetStatus
+from slack_bolt.context.set_suggested_prompts.set_suggested_prompts import SetSuggestedPrompts
from slack_bolt.middleware import Middleware
-from slack_bolt.request.payload_utils import is_assistant_event, to_event
+from slack_bolt.context.assistant.assistant_utilities import AssistantUtilities
+from slack_bolt.request.payload_utils import (
+ is_app_home_opened_event,
+ is_assistant_event,
+ is_assistant_thread_context_changed_event,
+ is_assistant_thread_started_event,
+ is_im_message_event,
+ to_event,
+)
from slack_bolt.request.request import BoltRequest
from slack_bolt.response.response import BoltResponse
class AttachingConversationKwargs(Middleware):
-
thread_context_store: Optional[AssistantThreadContextStore]
def __init__(self, thread_context_store: Optional[AssistantThreadContextStore] = None):
@@ -19,32 +26,48 @@ def __init__(self, thread_context_store: Optional[AssistantThreadContextStore] =
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,
- )
+ if event is None:
+ return next()
+ if req.context.channel_id is None:
+ return next()
+
+ if is_assistant_event(req.body):
+ # TODO: eventually we might remove this assistant specific logic
+ 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["get_thread_context"] = assistant.get_thread_context
+ req.context["save_thread_context"] = assistant.save_thread_context
+
+ if (
+ is_im_message_event(req.body)
+ or is_assistant_thread_started_event(req.body)
+ or is_assistant_thread_context_changed_event(req.body)
+ or is_app_home_opened_event(req.body, tab="messages")
+ ):
+ req.context["set_suggested_prompts"] = SetSuggestedPrompts(
+ client=req.context.client,
+ channel_id=req.context.channel_id,
+ thread_ts=req.context.thread_ts,
+ )
+
+ # TODO: in the future we might want to introduce a "proper" extract_ts utility
+ thread_ts_or_ts = req.context.thread_ts or event.get("ts")
+ if thread_ts_or_ts:
+ req.context["set_status"] = SetStatus(
+ client=req.context.client,
+ channel_id=req.context.channel_id,
+ thread_ts=thread_ts_or_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_or_ts,
+ )
return next()
diff --git a/slack_bolt/middleware/authorization/single_team_authorization.py b/slack_bolt/middleware/authorization/single_team_authorization.py
index c2bc1488c..21fb115e1 100644
--- a/slack_bolt/middleware/authorization/single_team_authorization.py
+++ b/slack_bolt/middleware/authorization/single_team_authorization.py
@@ -30,6 +30,7 @@ def __init__(
Args:
auth_test_result: The initial `auth.test` API call result.
base_logger: The base logger
+ user_facing_authorize_error_message: The message shown to the end-user when authorization fails
"""
self.auth_test_result = auth_test_result
self.logger = get_bolt_logger(SingleTeamAuthorization, base_logger=base_logger)
diff --git a/slack_bolt/middleware/middleware.py b/slack_bolt/middleware/middleware.py
index 560499d6c..2a566a5b8 100644
--- a/slack_bolt/middleware/middleware.py
+++ b/slack_bolt/middleware/middleware.py
@@ -20,6 +20,7 @@ def process(
next: Callable[[], BoltResponse],
) -> Optional[BoltResponse]:
"""Processes a request data before other middleware and listeners.
+
A middleware calls `next()` function if the chain should continue.
@app.middleware
@@ -47,5 +48,5 @@ def simple_middleware(req, resp, next_):
@property
def name(self) -> str:
- """The name of this middleware"""
+ """The name of this middleware."""
return f"{self.__module__}.{self.__class__.__name__}"
diff --git a/slack_bolt/middleware/request_verification/async_request_verification.py b/slack_bolt/middleware/request_verification/async_request_verification.py
index 3fb9e209b..99b86a63c 100644
--- a/slack_bolt/middleware/request_verification/async_request_verification.py
+++ b/slack_bolt/middleware/request_verification/async_request_verification.py
@@ -7,8 +7,9 @@
class AsyncRequestVerification(RequestVerification, AsyncMiddleware):
- """Verifies an incoming request by checking the validity of
- `x-slack-signature`, `x-slack-request-timestamp`, and its body data.
+ """Verifies an incoming request from Slack.
+
+ Checks the validity of `x-slack-signature`, `x-slack-request-timestamp`, and the request body data.
Refer to https://docs.slack.dev/authentication/verifying-requests-from-slack/ for details.
"""
diff --git a/slack_bolt/middleware/request_verification/request_verification.py b/slack_bolt/middleware/request_verification/request_verification.py
index 2cf7e361e..1425f7baf 100644
--- a/slack_bolt/middleware/request_verification/request_verification.py
+++ b/slack_bolt/middleware/request_verification/request_verification.py
@@ -1,5 +1,5 @@
from logging import Logger
-from typing import Callable, Dict, Any, Optional
+from typing import Any, Callable, Dict, Optional
from slack_sdk.signature import SignatureVerifier
@@ -11,8 +11,9 @@
class RequestVerification(Middleware):
def __init__(self, signing_secret: str, base_logger: Optional[Logger] = None):
- """Verifies an incoming request by checking the validity of
- `x-slack-signature`, `x-slack-request-timestamp`, and its body data.
+ """Verifies an incoming request from Slack.
+
+ Checks the validity of `x-slack-signature`, `x-slack-request-timestamp`, and the request body data.
Refer to https://docs.slack.dev/authentication/verifying-requests-from-slack/ for details.
@@ -20,9 +21,17 @@ def __init__(self, signing_secret: str, base_logger: Optional[Logger] = None):
signing_secret: The signing secret
base_logger: The base logger
"""
- self.verifier = SignatureVerifier(signing_secret=signing_secret)
+ self._signing_secret = signing_secret
+ self._verifier: Optional[SignatureVerifier] = None
self.logger = get_bolt_logger(RequestVerification, base_logger=base_logger)
+ @property
+ def verifier(self) -> SignatureVerifier:
+ # Defer initialization to avoid errors during start up
+ if self._verifier is None:
+ self._verifier = SignatureVerifier(signing_secret=self._signing_secret)
+ return self._verifier
+
def process(
self,
*,
@@ -49,7 +58,7 @@ def process(
@staticmethod
def _can_skip(mode: str, body: Dict[str, Any]) -> bool:
- return mode == "socket_mode" or (body is not None and body.get("ssl_check") == "1")
+ return mode == "socket_mode"
@staticmethod
def _build_error_response() -> BoltResponse:
@@ -57,5 +66,5 @@ def _build_error_response() -> BoltResponse:
def _debug_log_error(self, signature, timestamp, body) -> None:
self.logger.info(
- "Invalid request signature detected " f"(signature: {signature}, timestamp: {timestamp}, body: {body})"
+ f"Invalid request signature detected (signature: {signature}, timestamp: {timestamp}, body: {body})"
)
diff --git a/slack_bolt/middleware/ssl_check/ssl_check.py b/slack_bolt/middleware/ssl_check/ssl_check.py
index 88c5105ef..5e5d9ad9c 100644
--- a/slack_bolt/middleware/ssl_check/ssl_check.py
+++ b/slack_bolt/middleware/ssl_check/ssl_check.py
@@ -17,6 +17,7 @@ def __init__(
base_logger: Optional[Logger] = None,
):
"""Handles `ssl_check` requests.
+
Refer to https://docs.slack.dev/interactivity/implementing-slash-commands/ for details.
Args:
diff --git a/slack_bolt/oauth/async_oauth_flow.py b/slack_bolt/oauth/async_oauth_flow.py
index e7f0fa724..dc5adcb03 100644
--- a/slack_bolt/oauth/async_oauth_flow.py
+++ b/slack_bolt/oauth/async_oauth_flow.py
@@ -115,6 +115,7 @@ def sqlite3(
installation_store_bot_only: bool = False,
client: Optional[AsyncWebClient] = None,
logger: Optional[Logger] = None,
+ token_rotation_expiration_minutes: int = 120,
) -> "AsyncOAuthFlow":
client_id = client_id or os.environ["SLACK_CLIENT_ID"] # required
@@ -152,6 +153,7 @@ def sqlite3(
# Installation Management
installation_store=installation_store,
installation_store_bot_only=installation_store_bot_only,
+ token_rotation_expiration_minutes=token_rotation_expiration_minutes,
# state parameter related configurations
state_store=state_store,
state_cookie_name=state_cookie_name,
diff --git a/slack_bolt/oauth/internals.py b/slack_bolt/oauth/internals.py
index 05959817a..31da94207 100644
--- a/slack_bolt/oauth/internals.py
+++ b/slack_bolt/oauth/internals.py
@@ -55,7 +55,7 @@ def _build_callback_failure_response(
status: int = 500,
error: Optional[Exception] = None,
) -> BoltResponse:
- debug_message = "Handling an OAuth callback failure " f"(reason: {reason}, error: {error}, request: {request.query})"
+ debug_message = f"Handling an OAuth callback failure (reason: {reason}, error: {error}, request: {request.query})"
self._logger.debug(debug_message)
# Adding a bit more details to the error code to help installers understand what's happening.
diff --git a/slack_bolt/request/async_request.py b/slack_bolt/request/async_request.py
index 73891446e..c6a06f309 100644
--- a/slack_bolt/request/async_request.py
+++ b/slack_bolt/request/async_request.py
@@ -41,7 +41,6 @@ def __init__(
context: The context in this request.
mode: The mode used for this request. (either "http" or "socket_mode")
"""
-
if mode == "http":
# HTTP Mode
if body is not None and not isinstance(body, str):
diff --git a/slack_bolt/request/payload_utils.py b/slack_bolt/request/payload_utils.py
index 1ebf70d4f..b74238461 100644
--- a/slack_bolt/request/payload_utils.py
+++ b/slack_bolt/request/payload_utils.py
@@ -14,7 +14,7 @@ def to_event(body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
def to_message(body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
- if is_event(body) and body["event"]["type"] == "message":
+ if is_message_event(body):
return to_event(body)
return None
@@ -31,6 +31,25 @@ def is_workflow_step_execute(body: Dict[str, Any]) -> bool:
return is_event(body) and body["event"]["type"] == "workflow_step_execute" and "workflow_step" in body["event"]
+def is_message_event(body: Dict[str, Any]) -> bool:
+ if is_event(body):
+ return body["event"]["type"] == "message"
+ return False
+
+
+def is_any_im_message_event(body: Dict[str, Any]) -> bool:
+ if is_message_event(body):
+ # Any message event with no subtype or any subtype (message_changed, message_deleted, etc.)
+ return body["event"].get("channel_type") == "im"
+ return False
+
+
+def is_im_message_event(body: Dict[str, Any]) -> bool:
+ if is_any_im_message_event(body):
+ return body["event"].get("subtype") in (None, "file_share")
+ return False
+
+
def is_assistant_event(body: Dict[str, Any]) -> bool:
return is_event(body) and (
is_assistant_thread_started_event(body)
@@ -52,28 +71,24 @@ def is_assistant_thread_context_changed_event(body: Dict[str, Any]) -> bool:
return False
-def is_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
- if is_event(body):
- return body["event"]["type"] == "message" and body["event"].get("channel_type") == "im"
+def is_app_home_opened_event(body: Dict[str, Any], tab: Optional[str] = None) -> bool:
+ if is_event(body) and body["event"]["type"] == "app_home_opened":
+ if tab is not None:
+ return body["event"].get("tab") == tab
+ return True
return False
def is_user_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
- if is_event(body):
- return (
- is_message_event_in_assistant_thread(body)
- and body["event"].get("subtype") in (None, "file_share")
- and body["event"].get("thread_ts") is not None
- and body["event"].get("bot_id") is None
- )
+ if is_im_message_event(body):
+ return body["event"].get("thread_ts") is not None and body["event"].get("bot_id") is None
return False
def is_bot_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
- if is_event(body):
+ if is_any_im_message_event(body):
return (
- is_message_event_in_assistant_thread(body)
- and body["event"].get("subtype") is None
+ body["event"].get("subtype") is None
and body["event"].get("thread_ts") is not None
and body["event"].get("bot_id") is not None
)
@@ -82,14 +97,10 @@ def is_bot_message_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
def is_other_message_sub_event_in_assistant_thread(body: Dict[str, Any]) -> bool:
# message_changed, message_deleted etc.
- if is_event(body):
- return (
- is_message_event_in_assistant_thread(body)
- and not is_user_message_event_in_assistant_thread(body)
- and (
- _is_other_message_sub_event(body["event"].get("message"))
- or _is_other_message_sub_event(body["event"].get("previous_message"))
- )
+ if is_any_im_message_event(body):
+ return not is_user_message_event_in_assistant_thread(body) and (
+ _is_other_message_sub_event(body["event"].get("message"))
+ or _is_other_message_sub_event(body["event"].get("previous_message"))
)
return False
diff --git a/slack_bolt/version.py b/slack_bolt/version.py
index ebda7dafb..bc9ad30ef 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/"""
+"""Check the latest version at https://pypi.org/project/slack-bolt/."""
-__version__ = "1.28.0"
+__version__ = "1.30.0"
diff --git a/slack_bolt/workflows/step/async_step.py b/slack_bolt/workflows/step/async_step.py
index 7fa0ed858..b291fc1b2 100644
--- a/slack_bolt/workflows/step/async_step.py
+++ b/slack_bolt/workflows/step/async_step.py
@@ -28,7 +28,8 @@
class AsyncWorkflowStepBuilder:
- """Steps from apps
+ """Steps from apps.
+
Refer to https://docs.slack.dev/legacy/legacy-steps-from-apps/ for details.
"""
@@ -44,10 +45,9 @@ def __init__(
app_name: Optional[str] = None,
base_logger: Optional[Logger] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
This builder is supposed to be used as decorator.
@@ -86,10 +86,9 @@ def edit(
middleware: Optional[Union[Callable, AsyncMiddleware]] = None,
lazy: Optional[List[Callable[..., Awaitable[None]]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new edit listener with details.
@@ -139,10 +138,9 @@ def save(
middleware: Optional[Union[Callable, AsyncMiddleware]] = None,
lazy: Optional[List[Callable[..., Awaitable[None]]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new save listener with details.
@@ -192,10 +190,9 @@ def execute(
middleware: Optional[Union[Callable, AsyncMiddleware]] = None,
lazy: Optional[List[Callable[..., Awaitable[None]]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new execute listener with details.
@@ -239,10 +236,9 @@ async def _wrapper(*args, **kwargs):
return _inner
def build(self, base_logger: Optional[Logger] = None) -> "AsyncWorkflowStep":
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Constructs a WorkflowStep object. This method may raise an exception
if the builder doesn't have enough configurations to build the object.
@@ -337,10 +333,9 @@ def __init__(
app_name: Optional[str] = None,
base_logger: Optional[Logger] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Args:
callback_id: The callback_id for this step from app
@@ -383,10 +378,9 @@ def builder(
callback_id: Union[str, Pattern],
base_logger: Optional[Logger] = None,
) -> AsyncWorkflowStepBuilder:
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
"""
return AsyncWorkflowStepBuilder(callback_id, base_logger=base_logger)
diff --git a/slack_bolt/workflows/step/async_step_middleware.py b/slack_bolt/workflows/step/async_step_middleware.py
index 5801a51e6..09475a2cc 100644
--- a/slack_bolt/workflows/step/async_step_middleware.py
+++ b/slack_bolt/workflows/step/async_step_middleware.py
@@ -10,7 +10,7 @@
class AsyncWorkflowStepMiddleware(AsyncMiddleware):
- """Base middleware for step from app specific ones"""
+ """Base middleware for step from app specific ones."""
def __init__(self, step: AsyncWorkflowStep):
self.step = step
diff --git a/slack_bolt/workflows/step/step.py b/slack_bolt/workflows/step/step.py
index 4fca25717..57cab9bcd 100644
--- a/slack_bolt/workflows/step/step.py
+++ b/slack_bolt/workflows/step/step.py
@@ -23,7 +23,8 @@
class WorkflowStepBuilder:
- """Steps from apps
+ """Steps from apps.
+
Refer to https://docs.slack.dev/legacy/legacy-steps-from-apps/ for details.
"""
@@ -39,10 +40,9 @@ def __init__(
app_name: Optional[str] = None,
base_logger: Optional[Logger] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
This builder is supposed to be used as decorator.
@@ -81,10 +81,9 @@ def edit(
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new edit listener with details.
@@ -110,7 +109,6 @@ def edit_my_step(ack, configure):
middleware: Listener middleware
lazy: Lazy listeners
"""
-
if _is_used_without_argument(args):
func = args[0]
self._edit = self._to_listener("edit", func, matchers, middleware)
@@ -135,10 +133,9 @@ def save(
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new save listener with details.
@@ -188,10 +185,9 @@ def execute(
middleware: Optional[Union[Callable, Middleware]] = None,
lazy: Optional[List[Callable[..., None]]] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Registers a new execute listener with details.
@@ -235,10 +231,9 @@ def _wrapper(*args, **kwargs):
return _inner
def build(self, base_logger: Optional[Logger] = None) -> "WorkflowStep":
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Constructs a WorkflowStep object. This method may raise an exception
if the builder doesn't have enough configurations to build the object.
@@ -348,10 +343,9 @@ def __init__(
app_name: Optional[str] = None,
base_logger: Optional[Logger] = None,
):
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
Args:
callback_id: The callback_id for this step from app
@@ -390,10 +384,9 @@ def __init__(
@classmethod
def builder(cls, callback_id: Union[str, Pattern], base_logger: Optional[Logger] = None) -> WorkflowStepBuilder:
- """
- Deprecated:
- Steps from apps for legacy workflows are now deprecated.
- Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
+ """Deprecated: Steps from apps for legacy workflows are now deprecated.
+
+ Use new custom steps: https://docs.slack.dev/workflows/workflow-steps/
"""
return WorkflowStepBuilder(
callback_id,
diff --git a/slack_bolt/workflows/step/step_middleware.py b/slack_bolt/workflows/step/step_middleware.py
index 59af001a7..ff0616e6e 100644
--- a/slack_bolt/workflows/step/step_middleware.py
+++ b/slack_bolt/workflows/step/step_middleware.py
@@ -10,7 +10,7 @@
class WorkflowStepMiddleware(Middleware):
- """Base middleware for step from app specific ones"""
+ """Base middleware for step from app specific ones."""
def __init__(self, step: WorkflowStep):
self.step = step
diff --git a/tests/adapter_tests/asgi/test_asgi_http.py b/tests/adapter_tests/asgi/test_asgi_http.py
index 72b6434bf..f9f106461 100644
--- a/tests/adapter_tests/asgi/test_asgi_http.py
+++ b/tests/adapter_tests/asgi/test_asgi_http.py
@@ -223,6 +223,59 @@ async def test_url_verification(self):
assert response.headers.get("content-type") == "application/json;charset=utf-8"
assert_auth_test_count(self, 1)
+ @pytest.mark.asyncio
+ async def test_content_length_multibyte_body(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ def command_handler(ack):
+ ack(text="Hello ☃") # snowman is 3 bytes in UTF-8
+
+ app.command("/hello-world")(command_handler)
+
+ body = (
+ "token=verification_token"
+ "&team_id=T111"
+ "&team_domain=test-domain"
+ "&channel_id=C111"
+ "&channel_name=random"
+ "&user_id=W111"
+ "&user_name=primary-owner"
+ "&command=%2Fhello-world"
+ "&text=Hi"
+ "&enterprise_id=E111"
+ "&enterprise_name=Org+Name"
+ "&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT111%2F111%2Fxxxxx"
+ "&trigger_id=111.111.xxx"
+ )
+
+ headers = self.build_raw_headers(str(int(time())), body)
+
+ asgi_server = AsgiTestServer(SlackRequestHandler(app))
+ response = await asgi_server.http("POST", headers, body)
+
+ assert response.status_code == 200
+ content_length = int(response.headers.get("content-length"))
+ actual_bytes = len(response.body.encode("utf-8"))
+ assert content_length == actual_bytes
+
+ @pytest.mark.asyncio
+ async def test_multi_value_headers(self):
+ from slack_bolt.adapter.asgi.http_response import AsgiHttpResponse
+
+ headers = {
+ "set-cookie": ["cookie1=value1; Path=/", "cookie2=value2; Path=/"],
+ "content-type": ["text/html; charset=utf-8"],
+ }
+ response = AsgiHttpResponse(status=200, headers=headers, body="OK")
+
+ set_cookie_headers = [(name, value) for name, value in response.raw_headers if name == b"set-cookie"]
+ assert len(set_cookie_headers) == 2
+ assert set_cookie_headers[0] == (b"set-cookie", b"cookie1=value1; Path=/")
+ assert set_cookie_headers[1] == (b"set-cookie", b"cookie2=value2; Path=/")
+
@pytest.mark.asyncio
async def test_unsupported_method(self):
app = App(
diff --git a/tests/adapter_tests/asgi/test_asgi_lifespan.py b/tests/adapter_tests/asgi/test_asgi_lifespan.py
index 488a990f1..5b48f6b8a 100644
--- a/tests/adapter_tests/asgi/test_asgi_lifespan.py
+++ b/tests/adapter_tests/asgi/test_asgi_lifespan.py
@@ -1,5 +1,6 @@
import pytest
+from asgiref.testing import ApplicationCommunicator
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web import WebClient
@@ -59,6 +60,24 @@ async def test_shutdown(self):
assert response.type == "lifespan.shutdown.complete"
assert response.message == ""
+ @pytest.mark.asyncio
+ async def test_full_lifespan_cycle(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+
+ scope = {"type": "lifespan", "asgi": {"version": "3.0", "spec_version": "2.3"}}
+ communicator = ApplicationCommunicator(SlackRequestHandler(app), scope)
+
+ await communicator.send_input({"type": "lifespan.startup"})
+ startup_response = await communicator.receive_output(timeout=1)
+ assert startup_response["type"] == "lifespan.startup.complete"
+
+ await communicator.send_input({"type": "lifespan.shutdown"})
+ shutdown_response = await communicator.receive_output(timeout=1)
+ assert shutdown_response["type"] == "lifespan.shutdown.complete"
+
@pytest.mark.asyncio
async def test_failed_event(self):
app = App(
diff --git a/tests/adapter_tests/aws/test_aws_lambda.py b/tests/adapter_tests/aws/test_aws_lambda.py
index c2e888fb7..c3590938a 100644
--- a/tests/adapter_tests/aws/test_aws_lambda.py
+++ b/tests/adapter_tests/aws/test_aws_lambda.py
@@ -1,3 +1,4 @@
+import base64
import json
from time import time
from urllib.parse import quote
@@ -30,6 +31,8 @@ class LambdaContext:
def __init__(self, function_name: str):
self.function_name = function_name
self.invoked_function_arn = f"arn:aws:lambda:us-east-1:account-id:function:{self.function_name}"
+ self.aws_request_id = "52fdfc07-2182-154f-163f-5f0f9a621d72"
+ self.log_stream_name = "2024/03/01/[$LATEST]abcdef0123456789"
class TestAWSLambda:
@@ -66,10 +69,91 @@ def build_headers(self, timestamp: str, body: str):
"x-slack-request-timestamp": [timestamp],
}
+ def test_lambda_context_in_bolt_context(self):
+ app = App(client=self.web_client, signing_secret=self.signing_secret)
+ captured = {}
+
+ @app.middleware
+ def capture(context, next):
+ captured.update(context)
+ next()
+
+ app.event("app_mention")(lambda: None)
+ input = {
+ "token": "verification_token",
+ "team_id": "T111",
+ "api_app_id": "A111",
+ "event": {"type": "app_mention", "text": "hi", "user": "W222", "team": "T111", "channel": "C111"},
+ "type": "event_callback",
+ "event_id": "Ev111",
+ "event_time": 1595926230,
+ }
+ timestamp, body = str(int(time())), json.dumps(input)
+ event = {
+ "body": body,
+ "queryStringParameters": {},
+ "headers": self.build_headers(timestamp, body),
+ "requestContext": {"http": {"method": "POST"}},
+ "isBase64Encoded": False,
+ }
+ response = SlackRequestHandler(app).handle(event, self.context)
+ assert response["statusCode"] == 200
+ assert captured["aws_lambda_request_id"] == self.context.aws_request_id
+ assert captured["aws_lambda_log_stream_name"] == self.context.log_stream_name
+
def test_not_found(self):
response = not_found()
assert response["statusCode"] == 404
+ def test_null_fields_in_api_gateway_event(self):
+ app = App(client=self.web_client, signing_secret=self.signing_secret)
+ event = {
+ "httpMethod": "POST",
+ "requestContext": {"httpMethod": "POST"},
+ "headers": None,
+ "multiValueHeaders": None,
+ "queryStringParameters": None,
+ "body": "{}",
+ "isBase64Encoded": False,
+ }
+ response = SlackRequestHandler(app).handle(event, self.context)
+ assert response["statusCode"] == 401
+ assert event["headers"] is None
+
+ def test_missing_is_base64_encoded_and_null_body(self):
+ app = App(client=self.web_client, signing_secret=self.signing_secret)
+ event = {"requestContext": {"http": {"method": "POST"}}, "headers": {}, "body": "{}"}
+ assert SlackRequestHandler(app).handle(event, self.context)["statusCode"] == 401
+ event = {"requestContext": {"http": {"method": "POST"}}, "headers": {}, "body": None, "isBase64Encoded": True}
+ assert SlackRequestHandler(app).handle(event, self.context)["statusCode"] == 401
+
+ def test_base64_encoded_body(self):
+ app = App(client=self.web_client, signing_secret=self.signing_secret)
+
+ def event_handler():
+ pass
+
+ app.event("app_mention")(event_handler)
+ input = {
+ "token": "verification_token",
+ "team_id": "T111",
+ "api_app_id": "A111",
+ "event": {"type": "app_mention", "text": "<@W111> Hi", "user": "W222", "team": "T111", "channel": "C111"},
+ "type": "event_callback",
+ "event_id": "Ev111",
+ "event_time": 1595926230,
+ }
+ timestamp, body = str(int(time())), json.dumps(input)
+ event = {
+ "body": base64.b64encode(body.encode("utf-8")).decode("ascii"),
+ "queryStringParameters": None,
+ "headers": self.build_headers(timestamp, body),
+ "requestContext": {"http": {"method": "POST"}},
+ "isBase64Encoded": True,
+ }
+ response = SlackRequestHandler(app).handle(event, self.context)
+ assert response["statusCode"] == 200
+
def test_first_value(self):
assert _first_value({"foo": [1, 2, 3]}, "foo") == 1
assert _first_value({"foo": []}, "foo") is None
diff --git a/tests/adapter_tests/falcon/test_falcon.py b/tests/adapter_tests/falcon/test_falcon.py
index d7841a24a..4a2f34d36 100644
--- a/tests/adapter_tests/falcon/test_falcon.py
+++ b/tests/adapter_tests/falcon/test_falcon.py
@@ -205,3 +205,17 @@ def test_oauth(self):
response = client.simulate_get("/slack/install")
assert response.status_code == 200
assert "https://slack.com/oauth/v2/authorize?state=" in response.text
+
+ def test_get_no_oauth(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+ api = new_falcon_app()
+ resource = SlackAppResource(app)
+ api.add_route("/slack/events", resource)
+
+ client = testing.TestClient(api)
+ response = client.simulate_get("/slack/events")
+ assert response.status_code == 404
+ assert "The page is not found" in response.text
diff --git a/tests/adapter_tests/socket_mode/test_interactions_builtin.py b/tests/adapter_tests/socket_mode/test_interactions_builtin.py
index 2ecd52554..aec04d938 100644
--- a/tests/adapter_tests/socket_mode/test_interactions_builtin.py
+++ b/tests/adapter_tests/socket_mode/test_interactions_builtin.py
@@ -36,7 +36,7 @@ def teardown_method(self):
def test_interactions(self):
app = App(client=self.web_client)
- result = {"shortcut": False, "command": False}
+ result = {"shortcut": False, "command": False, "message": False}
@app.shortcut("do-something")
def shortcut_handler(ack):
@@ -48,6 +48,13 @@ def command_handler(ack):
result["command"] = True
ack()
+ @app.message("<@W111>")
+ def message_handler(ack, req):
+ result["message"] = req.headers.get("x-slack-retry-num") == ["1"] and req.headers.get(
+ "x-slack-retry-reason"
+ ) == ["timeout"]
+ ack()
+
handler = SocketModeHandler(
app_token="xapp-A111-222-xyz",
app=app,
@@ -66,5 +73,6 @@ def command_handler(ack):
time.sleep(2)
assert result["shortcut"] is True
assert result["command"] is True
+ assert result["message"] is True
finally:
handler.client.close()
diff --git a/tests/adapter_tests/socket_mode/test_interactions_websocket_client.py b/tests/adapter_tests/socket_mode/test_interactions_websocket_client.py
index ccaa89d3e..90e027f9d 100644
--- a/tests/adapter_tests/socket_mode/test_interactions_websocket_client.py
+++ b/tests/adapter_tests/socket_mode/test_interactions_websocket_client.py
@@ -37,7 +37,7 @@ def test_interactions(self):
app = App(client=self.web_client)
- result = {"shortcut": False, "command": False}
+ result = {"shortcut": False, "command": False, "message": False}
@app.shortcut("do-something")
def shortcut_handler(ack):
@@ -49,6 +49,13 @@ def command_handler(ack):
result["command"] = True
ack()
+ @app.message("<@W111>")
+ def message_handler(ack, req):
+ result["message"] = req.headers.get("x-slack-retry-num") == ["1"] and req.headers.get(
+ "x-slack-retry-reason"
+ ) == ["timeout"]
+ ack()
+
handler = SocketModeHandler(
app_token="xapp-A111-222-xyz",
app=app,
@@ -67,5 +74,6 @@ def command_handler(ack):
time.sleep(2)
assert result["shortcut"] is True
assert result["command"] is True
+ assert result["message"] is True
finally:
handler.client.close()
diff --git a/tests/adapter_tests/socket_mode/test_internals.py b/tests/adapter_tests/socket_mode/test_internals.py
new file mode 100644
index 000000000..fede30b48
--- /dev/null
+++ b/tests/adapter_tests/socket_mode/test_internals.py
@@ -0,0 +1,20 @@
+from slack_sdk.socket_mode.request import SocketModeRequest
+
+from slack_bolt.adapter.socket_mode.internals import build_headers, run_bolt_app
+
+
+class TestSocketModeInternals:
+ def test_build_retry_headers_without_retry(self):
+ req = SocketModeRequest(type="events_api", envelope_id="e1", payload={"type": "event_callback"})
+ assert build_headers(req) is None
+
+ def test_build_retry_headers_with_retry(self):
+ req = SocketModeRequest(
+ type="events_api",
+ envelope_id="e1",
+ payload={"type": "event_callback"},
+ retry_attempt=2,
+ retry_reason="http_timeout",
+ )
+ headers = build_headers(req)
+ assert headers == {"x-slack-retry-num": "2", "x-slack-retry-reason": "http_timeout"}
diff --git a/tests/adapter_tests/wsgi/test_wsgi_http.py b/tests/adapter_tests/wsgi/test_wsgi_http.py
index 63ac62627..c7fca2e25 100644
--- a/tests/adapter_tests/wsgi/test_wsgi_http.py
+++ b/tests/adapter_tests/wsgi/test_wsgi_http.py
@@ -89,6 +89,47 @@ def command_handler(ack):
assert response.headers.get("content-type") == "text/plain;charset=utf-8"
assert_auth_test_count(self, 1)
+ def test_ssl_check_param_does_not_bypass_request_verification(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ ssl_check_enabled=False,
+ )
+ command_called = False
+
+ def command_handler(ack):
+ nonlocal command_called
+ command_called = True
+ ack()
+
+ app.command("/hello-world")(command_handler)
+
+ body = (
+ "token=verification_token"
+ "&team_id=T111"
+ "&team_domain=test-domain"
+ "&channel_id=C111"
+ "&channel_name=random"
+ "&user_id=W111"
+ "&user_name=primary-owner"
+ "&command=%2Fhello-world"
+ "&text=Hi"
+ "&enterprise_id=E111"
+ "&enterprise_name=Org+Name"
+ "&response_url=https%3A%2F%2Fhooks.slack.com%2Fcommands%2FT111%2F111%2Fxxxxx"
+ "&trigger_id=111.111.xxx"
+ "&ssl_check=1"
+ )
+ headers = self.build_raw_headers("0", body)
+ headers["x-slack-signature"] = "v0=invalid"
+
+ wsgi_server = WsgiTestServer(SlackRequestHandler(app))
+ response = wsgi_server.http(method="POST", headers=headers, body=body)
+
+ assert response.status == "401 Unauthorized"
+ assert response.body == """{"error": "invalid request"}"""
+ assert command_called is False
+
def test_events(self):
app = App(
client=self.web_client,
diff --git a/tests/adapter_tests_async/socket_mode/test_async_aiohttp.py b/tests/adapter_tests_async/socket_mode/test_async_aiohttp.py
index e8077f10c..812806a8c 100644
--- a/tests/adapter_tests_async/socket_mode/test_async_aiohttp.py
+++ b/tests/adapter_tests_async/socket_mode/test_async_aiohttp.py
@@ -40,7 +40,7 @@ async def test_events(self):
app = AsyncApp(client=self.web_client)
- result = {"shortcut": False, "command": False}
+ result = {"shortcut": False, "command": False, "message": False}
@app.shortcut("do-something")
async def shortcut_handler(ack):
@@ -52,6 +52,13 @@ async def command_handler(ack):
result["command"] = True
await ack()
+ @app.message("<@W111>")
+ async def message_handler(ack, req):
+ result["message"] = req.headers.get("x-slack-retry-num") == ["1"] and req.headers.get(
+ "x-slack-retry-reason"
+ ) == ["timeout"]
+ await ack()
+
handler = AsyncSocketModeHandler(
app_token="xapp-A111-222-xyz",
app=app,
@@ -67,6 +74,7 @@ async def command_handler(ack):
await asyncio.sleep(2)
assert result["shortcut"] is True
assert result["command"] is True
+ assert result["message"] is True
finally:
await handler.client.close()
stop_socket_mode_server(self)
diff --git a/tests/adapter_tests_async/socket_mode/test_async_websockets.py b/tests/adapter_tests_async/socket_mode/test_async_websockets.py
index 84d20b2f9..fc27150ee 100644
--- a/tests/adapter_tests_async/socket_mode/test_async_websockets.py
+++ b/tests/adapter_tests_async/socket_mode/test_async_websockets.py
@@ -40,7 +40,7 @@ async def test_events(self):
app = AsyncApp(client=self.web_client)
- result = {"shortcut": False, "command": False}
+ result = {"shortcut": False, "command": False, "message": False}
@app.shortcut("do-something")
async def shortcut_handler(ack):
@@ -52,6 +52,13 @@ async def command_handler(ack):
result["command"] = True
await ack()
+ @app.message("<@W111>")
+ async def message_handler(ack, req):
+ result["message"] = req.headers.get("x-slack-retry-num") == ["1"] and req.headers.get(
+ "x-slack-retry-reason"
+ ) == ["timeout"]
+ await ack()
+
handler = AsyncSocketModeHandler(
app_token="xapp-A111-222-xyz",
app=app,
@@ -67,6 +74,7 @@ async def command_handler(ack):
await asyncio.sleep(2)
assert result["shortcut"] is True
assert result["command"] is True
+ assert result["message"] is True
finally:
await handler.client.close()
stop_socket_mode_server(self)
diff --git a/tests/adapter_tests_async/test_async_falcon.py b/tests/adapter_tests_async/test_async_falcon.py
index 6e3901fdf..d7a8c277a 100644
--- a/tests/adapter_tests_async/test_async_falcon.py
+++ b/tests/adapter_tests_async/test_async_falcon.py
@@ -2,8 +2,9 @@
from time import time
from urllib.parse import quote
+import pytest
import falcon
-from falcon import testing
+from falcon.testing import ASGIConductor
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web.async_client import AsyncWebClient
@@ -55,7 +56,8 @@ def build_headers(self, timestamp: str, body: str):
"x-slack-request-timestamp": timestamp,
}
- def test_events(self):
+ @pytest.mark.asyncio
+ async def test_events(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
@@ -92,16 +94,17 @@ async def event_handler():
resource = AsyncSlackAppResource(app)
api.add_route("/slack/events", resource)
- client = testing.TestClient(api)
- response = client.simulate_post(
- "/slack/events",
- body=body,
- headers=self.build_headers(timestamp, body),
- )
+ async with ASGIConductor(api) as conductor:
+ response = await conductor.simulate_post(
+ "/slack/events",
+ body=body,
+ headers=self.build_headers(timestamp, body),
+ )
assert response.status_code == 200
assert_auth_test_count(self, 1)
- def test_shortcuts(self):
+ @pytest.mark.asyncio
+ async def test_shortcuts(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
@@ -133,16 +136,17 @@ async def shortcut_handler(ack):
resource = AsyncSlackAppResource(app)
api.add_route("/slack/events", resource)
- client = testing.TestClient(api)
- response = client.simulate_post(
- "/slack/events",
- body=body,
- headers=self.build_headers(timestamp, body),
- )
+ async with ASGIConductor(api) as conductor:
+ response = await conductor.simulate_post(
+ "/slack/events",
+ body=body,
+ headers=self.build_headers(timestamp, body),
+ )
assert response.status_code == 200
assert_auth_test_count(self, 1)
- def test_commands(self):
+ @pytest.mark.asyncio
+ async def test_commands(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
@@ -174,16 +178,17 @@ async def command_handler(ack):
resource = AsyncSlackAppResource(app)
api.add_route("/slack/events", resource)
- client = testing.TestClient(api)
- response = client.simulate_post(
- "/slack/events",
- body=body,
- headers=self.build_headers(timestamp, body),
- )
+ async with ASGIConductor(api) as conductor:
+ response = await conductor.simulate_post(
+ "/slack/events",
+ body=body,
+ headers=self.build_headers(timestamp, body),
+ )
assert response.status_code == 200
assert_auth_test_count(self, 1)
- def test_oauth(self):
+ @pytest.mark.asyncio
+ async def test_oauth(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
@@ -197,9 +202,24 @@ def test_oauth(self):
resource = AsyncSlackAppResource(app)
api.add_route("/slack/install", resource)
- client = testing.TestClient(api)
- response = client.simulate_get("/slack/install")
+ async with ASGIConductor(api) as conductor:
+ response = await conductor.simulate_get("/slack/install")
assert response.status_code == 200
assert response.headers.get("content-type") == "text/html; charset=utf-8"
assert response.headers.get("content-length") == "607"
assert "https://slack.com/oauth/v2/authorize?state=" in response.text
+
+ @pytest.mark.asyncio
+ async def test_get_no_oauth(self):
+ app = AsyncApp(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ )
+ api = new_falcon_app()
+ resource = AsyncSlackAppResource(app)
+ api.add_route("/slack/events", resource)
+
+ async with ASGIConductor(api) as conductor:
+ response = await conductor.simulate_get("/slack/events")
+ assert response.status_code == 404
+ assert "The page is not found" in response.text
diff --git a/tests/mock_asgi_server.py b/tests/mock_asgi_server.py
index e71a0d3cb..0b29a3e5a 100644
--- a/tests/mock_asgi_server.py
+++ b/tests/mock_asgi_server.py
@@ -1,28 +1,44 @@
-from typing import Iterable, Tuple, Union
+from typing import Iterable, Tuple
+
+from asgiref.testing import ApplicationCommunicator
+
from slack_bolt.adapter.asgi.base_handler import BaseSlackRequestHandler
ENCODING = "utf-8"
class AsgiTestServerResponse:
- def __init__(self):
- self.status_code: int = None
- self._headers: Iterable[Tuple[bytes, bytes]] = []
- self._body: bytearray = bytearray(b"")
+ def __init__(
+ self,
+ status_code: int,
+ headers: Iterable[Tuple[bytes, bytes]] = (),
+ body: bytes = b"",
+ ):
+ self.status_code = status_code
+ self._headers = headers
+ self._body = body
@property
- def body(self):
+ def body(self) -> str:
return self._body.decode(ENCODING)
@property
- def headers(self):
- return {header[0].decode(ENCODING): header[1].decode(ENCODING) for header in self._headers}
+ def headers(self) -> dict:
+ result = {}
+ for header in self._headers:
+ key = header[0].decode(ENCODING)
+ if key not in result:
+ result[key] = header[1].decode(ENCODING)
+ return result
+
+ def get_headers_list(self, name: str) -> list:
+ return [header[1].decode(ENCODING) for header in self._headers if header[0].decode(ENCODING) == name]
class AsgiTestServerLifespanResponse:
- def __init__(self):
- self.type: str = None
- self.message: str = ""
+ def __init__(self, type: str, message: str = ""):
+ self.type = type
+ self.message = message
class AsgiTestServer:
@@ -61,22 +77,17 @@ async def http(
},
)
- async def receive():
- return {"type": "http.request", "body": bytes(body, ENCODING), "more_body": False}
+ communicator = ApplicationCommunicator(self.asgi_app, scope)
+ await communicator.send_input({"type": "http.request", "body": bytes(body, ENCODING), "more_body": False})
- response = AsgiTestServerResponse()
+ response_start = await communicator.receive_output(timeout=1)
+ response_body = await communicator.receive_output(timeout=1)
- async def send(event):
- if event["type"] == "http.response.start":
- response.status_code = event["status"]
- response._headers = event["headers"]
- elif event["type"] == "http.response.body":
- response._body.extend(event["body"])
- else:
- raise TypeError(f"Sent type {event['type']} in response {event} is not valid")
-
- await self.asgi_app(scope, receive, send)
- return response
+ return AsgiTestServerResponse(
+ status_code=response_start["status"],
+ headers=response_start.get("headers", []),
+ body=response_body.get("body", b""),
+ )
async def lifespan(self, event: str) -> AsgiTestServerLifespanResponse:
"""This implements the server side behavior of the lifespan event
@@ -92,17 +103,20 @@ async def lifespan(self, event: str) -> AsgiTestServerLifespanResponse:
},
)
- async def receive():
- return {"type": f"lifespan.{event}"}
+ communicator = ApplicationCommunicator(self.asgi_app, scope)
+ await communicator.send_input({"type": f"lifespan.{event}"})
- response = AsgiTestServerLifespanResponse()
+ result = await communicator.receive_output(timeout=1)
- async def send(event: dict):
- response.type = event["type"]
- response.message = event.get("message", "")
+ # Send shutdown so the handler exits cleanly
+ if event == "startup":
+ await communicator.send_input({"type": "lifespan.shutdown"})
+ await communicator.receive_output(timeout=1)
- await self.asgi_app(scope, receive, send)
- return response
+ return AsgiTestServerLifespanResponse(
+ type=result["type"],
+ message=result.get("message", ""),
+ )
async def websocket(self) -> None:
"""This is not implemented"""
@@ -113,10 +127,6 @@ async def websocket(self) -> None:
},
)
- async def receive():
- return {}
-
- async def send(event: dict):
- print(event)
-
- await self.asgi_app(scope, receive, send)
+ communicator = ApplicationCommunicator(self.asgi_app, scope)
+ await communicator.send_input({})
+ await communicator.receive_output(timeout=1)
diff --git a/tests/mock_web_api_server/__init__.py b/tests/mock_web_api_server/__init__.py
index e164d4f4a..adf4c19ea 100644
--- a/tests/mock_web_api_server/__init__.py
+++ b/tests/mock_web_api_server/__init__.py
@@ -27,9 +27,9 @@ def assert_received_request_count(test: TestCase, path: str, min_count: int, tim
while time.time() - start_time < timeout:
try:
received_count = test.received_requests.get(path, 0)
- assert (
- received_count == min_count
- ), f"Expected {min_count} '{path}' {'requests' if min_count > 1 else 'request'}, but got {received_count}!"
+ assert received_count == min_count, (
+ f"Expected {min_count} '{path}' {'requests' if min_count > 1 else 'request'}, but got {received_count}!"
+ )
return
except Exception as e:
error = e
@@ -68,9 +68,9 @@ async def assert_received_request_count_async(test: TestCase, path: str, min_cou
while time.time() - start_time < timeout:
try:
received_count = await test.received_requests.get_async(path, 0)
- assert (
- received_count == min_count
- ), f"Expected {min_count} '{path}' {'requests' if min_count > 1 else 'request'}, but got {received_count}!"
+ assert received_count == min_count, (
+ f"Expected {min_count} '{path}' {'requests' if min_count > 1 else 'request'}, but got {received_count}!"
+ )
return
except Exception as e:
error = e
diff --git a/tests/mock_wsgi_server.py b/tests/mock_wsgi_server.py
index a389a898e..7e8bad2e8 100644
--- a/tests/mock_wsgi_server.py
+++ b/tests/mock_wsgi_server.py
@@ -1,4 +1,7 @@
-from typing import Dict, Iterable, Optional, Tuple
+import io
+from typing import Any, Callable, Dict, List, Optional, Tuple
+from wsgiref.util import setup_testing_defaults
+from wsgiref.validate import validator
from slack_bolt.adapter.wsgi import SlackRequestHandler
@@ -6,37 +9,49 @@
class WsgiTestServerResponse:
- def __init__(self):
+ def __init__(self) -> None:
self.status: Optional[str] = None
- self._headers: Iterable[Tuple[str, str]] = []
- self._body: Iterable[bytes] = []
+ self._headers: List[Tuple[str, str]] = []
+ self._body: List[bytes] = []
@property
def headers(self) -> Dict[str, str]:
return {header[0]: header[1] for header in self._headers}
@property
- def body(self, length: int = 0) -> str:
- return "".join([chunk.decode(ENCODING) for chunk in self._body[length:]])
+ def body(self) -> str:
+ return "".join([chunk.decode(ENCODING) for chunk in self._body])
class MockReadable:
+ """PEP 3333 compliant input stream.
+
+ Implements read, readline, readlines, and __iter__ as required
+ by the WSGI specification for wsgi.input.
+ """
+
def __init__(self, body: str):
self.body = body
- self._body = bytes(body, ENCODING)
+ self._stream = io.BytesIO(bytes(body, ENCODING))
def get_content_length(self) -> int:
- return len(self._body)
+ return len(self.body.encode(ENCODING))
+
+ def read(self, size: int = -1) -> bytes:
+ if size == -1:
+ return self._stream.read()
+ return self._stream.read(size)
+
+ def readline(self, size: int = -1) -> bytes:
+ if size == -1:
+ return self._stream.readline()
+ return self._stream.readline(size)
- def read(self, size: int) -> bytes:
- if size < 0:
- raise ValueError("Size must be positive.")
- if size == 0:
- return b""
- # The body can only be read once
- _body = self._body[:size]
- self._body = b""
- return _body
+ def readlines(self, hint: int = -1) -> List[bytes]:
+ return self._stream.readlines(hint)
+
+ def __iter__(self):
+ return iter(self._stream)
class WsgiTestServer:
@@ -44,29 +59,26 @@ def __init__(
self,
wsgi_app: SlackRequestHandler,
root_path: str = "",
- version: Tuple[int, int] = (1, 0),
- multithread: bool = False,
- multiprocess: bool = False,
- run_once: bool = False,
input_terminated: bool = True,
- server_software: bool = "mock/0.0.0",
+ server_software: str = "mock/0.0.0",
url_scheme: str = "https",
remote_addr: str = "127.0.0.1",
remote_port: str = "63263",
):
self.root_path = root_path
- self.wsgi_app = wsgi_app
- self.environ = {
- "wsgi.version": version,
- "wsgi.multithread": multithread,
- "wsgi.multiprocess": multiprocess,
- "wsgi.run_once": run_once,
- "wsgi.input_terminated": input_terminated,
- "SERVER_SOFTWARE": server_software,
- "wsgi.url_scheme": url_scheme,
- "REMOTE_ADDR": remote_addr,
- "REMOTE_PORT": remote_port,
- }
+ self.wsgi_app = validator(wsgi_app)
+ self.environ: Dict[str, Any] = {}
+ setup_testing_defaults(self.environ)
+ self.environ.update(
+ {
+ "wsgi.input_terminated": input_terminated,
+ "wsgi.errors": io.StringIO(),
+ "SERVER_SOFTWARE": server_software,
+ "wsgi.url_scheme": url_scheme,
+ "REMOTE_ADDR": remote_addr,
+ "REMOTE_PORT": remote_port,
+ }
+ )
def http(
self,
@@ -101,16 +113,29 @@ def http(
environ[f"HTTP_{header_key}"] = value
if body is not None:
- environ["wsgi.input"] = MockReadable(body)
+ readable = MockReadable(body)
+ environ["wsgi.input"] = readable
if "CONTENT_LENGTH" not in environ:
- environ["CONTENT_LENGTH"] = str(environ["wsgi.input"].get_content_length())
+ environ["CONTENT_LENGTH"] = str(readable.get_content_length())
+ else:
+ environ["wsgi.input"] = MockReadable("")
response = WsgiTestServerResponse()
- def start_response(status, headers):
+ def start_response(
+ status: str,
+ headers: List[Tuple[str, str]],
+ exc_info: Optional[Any] = None,
+ ) -> Callable[[bytes], object]:
response.status = status
response._headers = headers
-
- response._body = self.wsgi_app(environ=environ, start_response=start_response)
+ return lambda s: None
+
+ iterator = self.wsgi_app(environ, start_response)
+ try:
+ response._body = list(iterator)
+ finally:
+ if hasattr(iterator, "close"):
+ iterator.close()
return response
diff --git a/tests/scenario_tests/test_app.py b/tests/scenario_tests/test_app.py
index 9fe6f423f..5cdff39bf 100644
--- a/tests/scenario_tests/test_app.py
+++ b/tests/scenario_tests/test_app.py
@@ -96,6 +96,13 @@ def test_token_verification_enabled_False(self):
assert self.received_requests.get("/auth.test") is None
+ def test_socket_mode_app_without_signing_secret(self):
+ app = App(
+ client=self.web_client,
+ token_verification_enabled=False,
+ )
+ assert app is not None
+
# --------------------------
# multi teams auth
# --------------------------
diff --git a/tests/scenario_tests/test_app_actor_user_token.py b/tests/scenario_tests/test_app_actor_user_token.py
index 024c29e59..3ee5ebf25 100644
--- a/tests/scenario_tests/test_app_actor_user_token.py
+++ b/tests/scenario_tests/test_app_actor_user_token.py
@@ -111,35 +111,38 @@ def build_headers(self, timestamp: str, body: str):
}
def build_request(self, team_id: str = "T014GJXU940"):
- timestamp, body = str(int(time())), json.dumps(
- {
- "team_id": team_id,
- "enterprise_id": "E013Y3SHLAY",
- "context_team_id": team_id,
- "context_enterprise_id": "E013Y3SHLAY",
- "api_app_id": "A04TEM7H4S0",
- "event": {
- "type": "message",
- "files": [],
- "upload": False,
- "user": "W013QGS7BPF",
- "display_as_bot": False,
- "team": team_id,
- "channel": "C04T3ACM40K",
- "subtype": "file_share",
- },
- "type": "event_callback",
- "authorizations": [
- {
- "enterprise_id": None,
- "team_id": "T0G9PQBBK",
- "user_id": "W23456789",
- "is_bot": True,
- "is_enterprise_install": False,
- }
- ],
- "is_ext_shared_channel": True,
- }
+ timestamp, body = (
+ str(int(time())),
+ json.dumps(
+ {
+ "team_id": team_id,
+ "enterprise_id": "E013Y3SHLAY",
+ "context_team_id": team_id,
+ "context_enterprise_id": "E013Y3SHLAY",
+ "api_app_id": "A04TEM7H4S0",
+ "event": {
+ "type": "message",
+ "files": [],
+ "upload": False,
+ "user": "W013QGS7BPF",
+ "display_as_bot": False,
+ "team": team_id,
+ "channel": "C04T3ACM40K",
+ "subtype": "file_share",
+ },
+ "type": "event_callback",
+ "authorizations": [
+ {
+ "enterprise_id": None,
+ "team_id": "T0G9PQBBK",
+ "user_id": "W23456789",
+ "is_bot": True,
+ "is_enterprise_install": False,
+ }
+ ],
+ "is_ext_shared_channel": True,
+ }
+ ),
)
return BoltRequest(body=body, headers=self.build_headers(timestamp, body))
diff --git a/tests/scenario_tests/test_app_installation_store.py b/tests/scenario_tests/test_app_installation_store.py
index 7434ee3e4..277938547 100644
--- a/tests/scenario_tests/test_app_installation_store.py
+++ b/tests/scenario_tests/test_app_installation_store.py
@@ -101,27 +101,30 @@ def build_headers(self, timestamp: str, body: str):
}
def build_app_mention_request(self):
- timestamp, body = str(int(time())), json.dumps(
- {
- "token": "verification_token",
- "team_id": "T111",
- "enterprise_id": "E111",
- "api_app_id": "A111",
- "event": {
- "client_msg_id": "9cbd4c5b-7ddf-4ede-b479-ad21fca66d63",
- "type": "app_mention",
- "text": "<@W111> Hi there!",
- "user": "W222",
- "ts": "1595926230.009600",
- "team": "T111",
- "channel": "C111",
- "event_ts": "1595926230.009600",
- },
- "type": "event_callback",
- "event_id": "Ev111",
- "event_time": 1595926230,
- "authed_users": ["W111"],
- }
+ timestamp, body = (
+ str(int(time())),
+ json.dumps(
+ {
+ "token": "verification_token",
+ "team_id": "T111",
+ "enterprise_id": "E111",
+ "api_app_id": "A111",
+ "event": {
+ "client_msg_id": "9cbd4c5b-7ddf-4ede-b479-ad21fca66d63",
+ "type": "app_mention",
+ "text": "<@W111> Hi there!",
+ "user": "W222",
+ "ts": "1595926230.009600",
+ "team": "T111",
+ "channel": "C111",
+ "event_ts": "1595926230.009600",
+ },
+ "type": "event_callback",
+ "event_id": "Ev111",
+ "event_time": 1595926230,
+ "authed_users": ["W111"],
+ }
+ ),
)
return BoltRequest(body=body, headers=self.build_headers(timestamp, body))
diff --git a/tests/scenario_tests/test_events_assistant.py b/tests/scenario_tests/test_events_assistant.py
index a1c3f1343..c95296154 100644
--- a/tests/scenario_tests/test_events_assistant.py
+++ b/tests/scenario_tests/test_events_assistant.py
@@ -409,7 +409,7 @@ def build_payload(event: dict) -> dict:
"user_profile": {},
"thread_ts": "1726133698.626339",
"parent_user_id": "W222",
- "channel": "D111",
+ "channel": "C111",
"event_ts": "1726133700.887259",
"channel_type": "channel",
}
@@ -444,7 +444,7 @@ def build_payload(event: dict) -> dict:
"reply_users": ["U222", "W111"],
"is_locked": False,
},
- "channel": "D111",
+ "channel": "C111",
"hidden": True,
"ts": "1726133701.028300",
"event_ts": "1726133701.028300",
diff --git a/tests/scenario_tests/test_events_ignore_self.py b/tests/scenario_tests/test_events_ignore_self.py
index db7d07ea8..3c66f3278 100644
--- a/tests/scenario_tests/test_events_ignore_self.py
+++ b/tests/scenario_tests/test_events_ignore_self.py
@@ -100,6 +100,7 @@ def handle_app_mention(say):
"type": "message",
"channel": "C111",
"ts": "1599529504.000400",
+ "channel_type": "channel",
},
"reaction": "heart_eyes",
"item_user": "W111",
diff --git a/tests/scenario_tests/test_function.py b/tests/scenario_tests/test_function.py
index 1e5e1c423..539e0fccc 100644
--- a/tests/scenario_tests/test_function.py
+++ b/tests/scenario_tests/test_function.py
@@ -189,8 +189,7 @@ def fake_sleep(duration):
assert response.status == 404
assert_auth_test_count(self, 1)
assert elapsed_seconds == timeout + 1, (
- f"Expected handler to time out after {timeout + 1} time.sleep calls, "
- f"but it was called {elapsed_seconds} times"
+ f"Expected handler to time out after {timeout + 1} time.sleep calls, but it was called {elapsed_seconds} times"
)
def test_warning_when_timeout_improperly_set(self, caplog):
diff --git a/tests/scenario_tests/test_slash_command.py b/tests/scenario_tests/test_slash_command.py
index 1db13ecca..ae7e7c53b 100644
--- a/tests/scenario_tests/test_slash_command.py
+++ b/tests/scenario_tests/test_slash_command.py
@@ -93,6 +93,34 @@ def test_failure(self):
assert response.status == 404
assert_auth_test_count(self, 1)
+ def test_ssl_check_param_does_not_bypass_request_verification(self):
+ app = App(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ ssl_check_enabled=False,
+ )
+ command_called = False
+
+ def command_handler(ack):
+ nonlocal command_called
+ command_called = True
+ ack()
+
+ app.command("/hello-world")(command_handler)
+
+ request = BoltRequest(
+ body=f"{slash_command_body}&ssl_check=1",
+ headers={
+ "content-type": ["application/x-www-form-urlencoded"],
+ "x-slack-signature": ["v0=invalid"],
+ "x-slack-request-timestamp": ["0"],
+ },
+ )
+ response = app.dispatch(request)
+ assert response.status == 401
+ assert response.body == """{"error": "invalid request"}"""
+ assert command_called is False
+
slash_command_body = (
"token=verification_token"
diff --git a/tests/scenario_tests_async/test_app_actor_user_token.py b/tests/scenario_tests_async/test_app_actor_user_token.py
index 0028096be..eb4e2e7ad 100644
--- a/tests/scenario_tests_async/test_app_actor_user_token.py
+++ b/tests/scenario_tests_async/test_app_actor_user_token.py
@@ -60,35 +60,38 @@ def build_headers(self, timestamp: str, body: str):
}
def build_request(self, team_id: str = "T014GJXU940") -> AsyncBoltRequest:
- timestamp, body = str(int(time())), json.dumps(
- {
- "team_id": team_id,
- "enterprise_id": "E013Y3SHLAY",
- "context_team_id": team_id,
- "context_enterprise_id": "E013Y3SHLAY",
- "api_app_id": "A04TEM7H4S0",
- "event": {
- "type": "message",
- "files": [],
- "upload": False,
- "user": "W013QGS7BPF",
- "display_as_bot": False,
- "team": team_id,
- "channel": "C04T3ACM40K",
- "subtype": "file_share",
- },
- "type": "event_callback",
- "authorizations": [
- {
- "enterprise_id": None,
- "team_id": "T0G9PQBBK",
- "user_id": "W23456789",
- "is_bot": True,
- "is_enterprise_install": False,
- }
- ],
- "is_ext_shared_channel": True,
- }
+ timestamp, body = (
+ str(int(time())),
+ json.dumps(
+ {
+ "team_id": team_id,
+ "enterprise_id": "E013Y3SHLAY",
+ "context_team_id": team_id,
+ "context_enterprise_id": "E013Y3SHLAY",
+ "api_app_id": "A04TEM7H4S0",
+ "event": {
+ "type": "message",
+ "files": [],
+ "upload": False,
+ "user": "W013QGS7BPF",
+ "display_as_bot": False,
+ "team": team_id,
+ "channel": "C04T3ACM40K",
+ "subtype": "file_share",
+ },
+ "type": "event_callback",
+ "authorizations": [
+ {
+ "enterprise_id": None,
+ "team_id": "T0G9PQBBK",
+ "user_id": "W23456789",
+ "is_bot": True,
+ "is_enterprise_install": False,
+ }
+ ],
+ "is_ext_shared_channel": True,
+ }
+ ),
)
return AsyncBoltRequest(body=body, headers=self.build_headers(timestamp, body))
diff --git a/tests/scenario_tests_async/test_events_assistant.py b/tests/scenario_tests_async/test_events_assistant.py
index edc77ecf3..9e1176c74 100644
--- a/tests/scenario_tests_async/test_events_assistant.py
+++ b/tests/scenario_tests_async/test_events_assistant.py
@@ -483,7 +483,7 @@ def build_payload(event: dict) -> dict:
"user_profile": {},
"thread_ts": "1726133698.626339",
"parent_user_id": "W222",
- "channel": "D111",
+ "channel": "C111",
"event_ts": "1726133700.887259",
"channel_type": "channel",
}
@@ -518,7 +518,7 @@ def build_payload(event: dict) -> dict:
"reply_users": ["U222", "W111"],
"is_locked": False,
},
- "channel": "D111",
+ "channel": "C111",
"hidden": True,
"ts": "1726133701.028300",
"event_ts": "1726133701.028300",
diff --git a/tests/scenario_tests_async/test_events_ignore_self.py b/tests/scenario_tests_async/test_events_ignore_self.py
index 7ec9d0cce..fa398a907 100644
--- a/tests/scenario_tests_async/test_events_ignore_self.py
+++ b/tests/scenario_tests_async/test_events_ignore_self.py
@@ -89,6 +89,7 @@ async def test_self_events_disabled(self):
"type": "message",
"channel": "C111",
"ts": "1599529504.000400",
+ "channel_type": "channel",
},
"reaction": "heart_eyes",
"item_user": "W111",
diff --git a/tests/scenario_tests_async/test_function.py b/tests/scenario_tests_async/test_function.py
index ce9080e36..0cbcf67c7 100644
--- a/tests/scenario_tests_async/test_function.py
+++ b/tests/scenario_tests_async/test_function.py
@@ -193,7 +193,7 @@ async def fake_sleep(duration):
assert response.status == 404
await assert_auth_test_count_async(self, 1)
assert elapsed_seconds == timeout + 1, (
- f"Expected handler to time out after {timeout + 1} sleep calls, " f"but it was called {elapsed_seconds} times"
+ f"Expected handler to time out after {timeout + 1} sleep calls, but it was called {elapsed_seconds} times"
)
@pytest.mark.asyncio
diff --git a/tests/scenario_tests_async/test_slash_command.py b/tests/scenario_tests_async/test_slash_command.py
index 1ac02bce7..918ccba87 100644
--- a/tests/scenario_tests_async/test_slash_command.py
+++ b/tests/scenario_tests_async/test_slash_command.py
@@ -100,6 +100,35 @@ async def test_failure(self):
assert response.status == 404
await assert_auth_test_count_async(self, 1)
+ @pytest.mark.asyncio
+ async def test_ssl_check_param_does_not_bypass_request_verification(self):
+ app = AsyncApp(
+ client=self.web_client,
+ signing_secret=self.signing_secret,
+ ssl_check_enabled=False,
+ )
+ command_called = False
+
+ async def command_handler(ack):
+ nonlocal command_called
+ command_called = True
+ await ack()
+
+ app.command("/hello-world")(command_handler)
+
+ request = AsyncBoltRequest(
+ body=f"{slash_command_body}&ssl_check=1",
+ headers={
+ "content-type": ["application/x-www-form-urlencoded"],
+ "x-slack-signature": ["v0=invalid"],
+ "x-slack-request-timestamp": ["0"],
+ },
+ )
+ response = await app.async_dispatch(request)
+ assert response.status == 401
+ assert response.body == """{"error": "invalid request"}"""
+ assert command_called is False
+
slash_command_body = (
"token=verification_token"
diff --git a/tests/slack_bolt/context/test_say_stream.py b/tests/slack_bolt/context/test_say_stream.py
index 29d244a65..04a52e419 100644
--- a/tests/slack_bolt/context/test_say_stream.py
+++ b/tests/slack_bolt/context/test_say_stream.py
@@ -1,21 +1,14 @@
import pytest
+from unittest.mock import patch, MagicMock
+
from slack_sdk import WebClient
from slack_bolt.context.say_stream.say_stream import SayStream
-from tests.mock_web_api_server import cleanup_mock_web_api_server, setup_mock_web_api_server
class TestSayStream:
- default_chat_stream_buffer_size = WebClient.chat_stream.__kwdefaults__["buffer_size"]
-
def setup_method(self):
- setup_mock_web_api_server(self)
- valid_token = "xoxb-valid"
- mock_api_server_base_url = "http://localhost:8888"
- self.web_client = WebClient(token=valid_token, base_url=mock_api_server_base_url)
-
- def teardown_method(self):
- cleanup_mock_web_api_server(self)
+ self.web_client = WebClient(token="xoxb-valid")
def test_missing_channel_raises(self):
say_stream = SayStream(client=self.web_client, channel=None, thread_ts="111.222")
@@ -35,16 +28,17 @@ def test_default_params(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = say_stream()
-
- assert stream._buffer_size == self.default_chat_stream_buffer_size
- assert stream._stream_args == {
- "channel": "C111",
- "thread_ts": "111.222",
- "recipient_team_id": "T111",
- "recipient_user_id": "U111",
- "task_display_mode": None,
- }
+ with patch.object(self.web_client, "chat_stream", return_value=MagicMock()) as mock_chat_stream:
+ say_stream()
+ mock_chat_stream.assert_called_once_with(
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
def test_parameter_overrides(self):
say_stream = SayStream(
@@ -54,16 +48,17 @@ def test_parameter_overrides(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = say_stream(channel="C222", thread_ts="333.444", recipient_team_id="T222", recipient_user_id="U222")
-
- assert stream._buffer_size == self.default_chat_stream_buffer_size
- assert stream._stream_args == {
- "channel": "C222",
- "thread_ts": "333.444",
- "recipient_team_id": "T222",
- "recipient_user_id": "U222",
- "task_display_mode": None,
- }
+ with patch.object(self.web_client, "chat_stream", return_value=MagicMock()) as mock_chat_stream:
+ say_stream(channel="C222", thread_ts="333.444", recipient_team_id="T222", recipient_user_id="U222")
+ mock_chat_stream.assert_called_once_with(
+ channel="C222",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ thread_ts="333.444",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
def test_buffer_size_overrides(self):
say_stream = SayStream(
@@ -73,19 +68,41 @@ def test_buffer_size_overrides(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = say_stream(
- buffer_size=100,
- channel="C222",
- thread_ts="333.444",
- recipient_team_id="T222",
- recipient_user_id="U222",
- )
+ with patch.object(self.web_client, "chat_stream", return_value=MagicMock()) as mock_chat_stream:
+ say_stream(
+ buffer_size=100,
+ channel="C222",
+ thread_ts="333.444",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ )
+ mock_chat_stream.assert_called_once_with(
+ buffer_size=100,
+ channel="C222",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ thread_ts="333.444",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
- assert stream._buffer_size == 100
- assert stream._stream_args == {
- "channel": "C222",
- "thread_ts": "333.444",
- "recipient_team_id": "T222",
- "recipient_user_id": "U222",
- "task_display_mode": None,
- }
+ def test_authorship_overrides(self):
+ say_stream = SayStream(
+ client=self.web_client,
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
+ )
+ with patch.object(self.web_client, "chat_stream", return_value=MagicMock()) as mock_chat_stream:
+ say_stream(icon_emoji=":maple_leaf:", username="Charlie Brown")
+ mock_chat_stream.assert_called_once_with(
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
+ icon_emoji=":maple_leaf:",
+ icon_url=None,
+ username="Charlie Brown",
+ )
diff --git a/tests/slack_bolt/context/test_set_status.py b/tests/slack_bolt/context/test_set_status.py
index fe998df5e..bb5807e96 100644
--- a/tests/slack_bolt/context/test_set_status.py
+++ b/tests/slack_bolt/context/test_set_status.py
@@ -32,6 +32,15 @@ def test_set_status_loading_messages(self):
)
assert response.status_code == 200
+ def test_set_status_authorship(self):
+ set_status = SetStatus(client=self.web_client, channel_id="C111", thread_ts="123.123")
+ response: SlackResponse = set_status(
+ status="Thinking...",
+ icon_emoji=":maple_leaf:",
+ username="Charlie Brown",
+ )
+ assert response.status_code == 200
+
def test_set_status_invalid(self):
set_status = SetStatus(client=self.web_client, channel_id="C111", thread_ts="123.123")
with pytest.raises(TypeError):
diff --git a/tests/slack_bolt/context/test_set_suggested_prompts.py b/tests/slack_bolt/context/test_set_suggested_prompts.py
index 792b974b5..a743d5656 100644
--- a/tests/slack_bolt/context/test_set_suggested_prompts.py
+++ b/tests/slack_bolt/context/test_set_suggested_prompts.py
@@ -1,3 +1,5 @@
+from unittest.mock import MagicMock, patch
+
import pytest
from slack_sdk import WebClient
from slack_sdk.web import SlackResponse
@@ -31,6 +33,47 @@ def test_set_suggested_prompts_objects(self):
)
assert response.status_code == 200
+ def test_set_suggested_prompts_without_thread_ts(self):
+ set_suggested_prompts = SetSuggestedPrompts(client=self.web_client, channel_id="C111")
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, return_value=MagicMock()
+ ) as mock_api:
+ set_suggested_prompts(prompts=["One", "Two"])
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts=None,
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
+ def test_set_suggested_prompts_thread_ts_override(self):
+ # The call-time thread_ts must win over the stored one
+ set_suggested_prompts = SetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="999.999")
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, return_value=MagicMock()
+ ) as mock_api:
+ set_suggested_prompts(prompts=["One", "Two"], thread_ts="123.123")
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts="123.123",
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
+ def test_set_suggested_prompts_thread_ts_override_falsy(self):
+ # An explicitly passed falsy thread_ts must be forwarded, not swallowed by the stored value
+ set_suggested_prompts = SetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="123.123")
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, return_value=MagicMock()
+ ) as mock_api:
+ set_suggested_prompts(prompts=["One", "Two"], thread_ts="")
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts="",
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
def test_set_suggested_prompts_invalid(self):
set_suggested_prompts = SetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="123.123")
with pytest.raises(TypeError):
diff --git a/tests/slack_bolt/logger/test_unmatched_suggestions.py b/tests/slack_bolt/logger/test_unmatched_suggestions.py
index b470fa061..2c0c82b99 100644
--- a/tests/slack_bolt/logger/test_unmatched_suggestions.py
+++ b/tests/slack_bolt/logger/test_unmatched_suggestions.py
@@ -22,7 +22,8 @@ def test_block_actions(self):
"block_id": "b",
"action_id": "action-id-value",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -30,7 +31,9 @@ def test_block_actions(self):
def handle_some_action(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_attachment_actions(self):
req: BoltRequest = BoltRequest(body=attachment_actions, mode="socket_mode")
@@ -46,7 +49,8 @@ def test_attachment_actions(self):
}
],
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -54,7 +58,9 @@ def test_attachment_actions(self):
def handle_some_action(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_app_mention_event(self):
req: BoltRequest = BoltRequest(body=app_mention_event, mode="socket_mode")
@@ -63,14 +69,17 @@ def test_app_mention_event(self):
"event": {"type": "app_mention"},
}
message = warning_unhandled_request(req)
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.event("app_mention")
def handle_app_mention_events(body, logger):
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_function_event(self):
req: BoltRequest = BoltRequest(body=function_event, mode="socket_mode")
@@ -79,7 +88,8 @@ def test_function_event(self):
"event": {"type": "function_executed"},
}
message = warning_unhandled_request(req)
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -94,7 +104,9 @@ def handle_some_function(ack, body, complete, fail, logger):
except Exception as e:
error = f"Failed to handle a function request (error: {{e}})"
fail(error=error)
-""" == message
+"""
+ == message
+ )
def test_commands(self):
req: BoltRequest = BoltRequest(body=slash_command, mode="socket_mode")
@@ -103,7 +115,8 @@ def test_commands(self):
"type": None,
"command": "/start-conv",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -111,7 +124,9 @@ def test_commands(self):
def handle_some_command(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_shortcut(self):
req: BoltRequest = BoltRequest(body=global_shortcut, mode="socket_mode")
@@ -120,7 +135,8 @@ def test_shortcut(self):
"type": "shortcut",
"callback_id": "test-shortcut",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -128,7 +144,9 @@ def test_shortcut(self):
def handle_shortcuts(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
req: BoltRequest = BoltRequest(body=message_shortcut, mode="socket_mode")
message = warning_unhandled_request(req)
@@ -136,7 +154,8 @@ def handle_shortcuts(ack, body, logger):
"type": "message_action",
"callback_id": "test-shortcut",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -144,7 +163,9 @@ def handle_shortcuts(ack, body, logger):
def handle_shortcuts(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_view(self):
req: BoltRequest = BoltRequest(body=view_submission, mode="socket_mode")
@@ -153,7 +174,8 @@ def test_view(self):
"type": "view_submission",
"view": {"type": "modal", "callback_id": "view-id"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -161,7 +183,9 @@ def test_view(self):
def handle_view_submission_events(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
req: BoltRequest = BoltRequest(body=view_closed, mode="socket_mode")
message = warning_unhandled_request(req)
@@ -169,7 +193,8 @@ def handle_view_submission_events(ack, body, logger):
"type": "view_closed",
"view": {"type": "modal", "callback_id": "view-id"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -177,7 +202,9 @@ def handle_view_submission_events(ack, body, logger):
def handle_view_closed_events(ack, body, logger):
ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_block_suggestion(self):
req: BoltRequest = BoltRequest(body=block_suggestion, mode="socket_mode")
@@ -189,14 +216,17 @@ def test_block_suggestion(self):
"action_id": "the-id",
"value": "search word",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.options("the-id")
def handle_some_options(ack):
ack(options=[ ... ])
-""" == message
+"""
+ == message
+ )
def test_dialog_suggestion(self):
req: BoltRequest = BoltRequest(body=dialog_suggestion, mode="socket_mode")
@@ -206,14 +236,17 @@ def test_dialog_suggestion(self):
"callback_id": "the-id",
"value": "search keyword",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.options({{"type": "dialog_suggestion", "callback_id": "the-id"}})
def handle_some_options(ack):
ack(options=[ ... ])
-""" == message
+"""
+ == message
+ )
def test_step(self):
req: BoltRequest = BoltRequest(body=step_edit_payload, mode="socket_mode")
@@ -222,7 +255,8 @@ def test_step(self):
"type": "workflow_step_edit",
"callback_id": "copy_review",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -235,14 +269,17 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
req: BoltRequest = BoltRequest(body=step_save_payload, mode="socket_mode")
message = warning_unhandled_request(req)
filtered_body = {
"type": "view_submission",
"view": {"type": "workflow_step", "callback_id": "copy_review"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -255,14 +292,17 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
req: BoltRequest = BoltRequest(body=step_execute_payload, mode="socket_mode")
message = warning_unhandled_request(req)
filtered_body = {
"type": "event_callback",
"event": {"type": "workflow_step_execute"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -275,7 +315,9 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
block_actions = {
diff --git a/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py b/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py
index b7785eb50..3f46a6b67 100644
--- a/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py
+++ b/tests/slack_bolt/middleware/attaching_conversation_kwargs/test_attaching_conversation_kwargs.py
@@ -4,6 +4,7 @@
from slack_bolt.request import BoltRequest
from slack_bolt.response import BoltResponse
from tests.scenario_tests.test_events_assistant import (
+ build_payload,
thread_started_event_body,
user_message_event_body,
channel_user_message_event_body,
@@ -16,6 +17,70 @@ def next():
ASSISTANT_KWARGS = ("say", "set_title", "set_suggested_prompts", "get_thread_context", "save_thread_context")
+# A top-level DM (not in a thread) is not an assistant thread, but set_suggested_prompts is still attached.
+top_level_im_message_event_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "A top-level DM, not in a thread",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# A bot-authored top-level DM is also in scope: set_suggested_prompts is attached for any IM message.
+bot_im_message_event_body = build_payload(
+ {
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "A DM authored by a bot",
+ "user": "UB111",
+ "bot_id": "B111",
+ "app_id": "A222",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# A file_share DM is in scope too (subtype "file_share" passes is_im_message_event).
+file_share_im_message_event_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "subtype": "file_share",
+ "ts": "1726133700.887259",
+ "text": "uploaded a file",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# Opening the Messages tab of App Home is in scope for set_suggested_prompts.
+app_home_opened_messages_event_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "messages",
+ "event_ts": "1726133700.887259",
+ }
+)
+
+# Opening the Home tab is NOT in scope: set_suggested_prompts should not be attached.
+app_home_opened_home_event_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "home",
+ "event_ts": "1726133700.887259",
+ }
+)
+
class TestAttachingConversationKwargs:
def test_assistant_event_attaches_kwargs(self):
@@ -46,6 +111,66 @@ def test_user_message_event_attaches_kwargs(self):
assert "say_stream" in req.context
assert "set_status" in req.context
+ def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self):
+ middleware = AttachingConversationKwargs()
+ req = BoltRequest(body=top_level_im_message_event_body, mode="socket_mode")
+ req.context["client"] = WebClient(token="xoxb-test")
+
+ resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+ assert "set_title" not in req.context
+ assert "say" not in req.context
+ assert "get_thread_context" not in req.context
+ assert "save_thread_context" not in req.context
+ assert "say_stream" in req.context
+ assert "set_status" in req.context
+
+ def test_bot_dm_attaches_suggested_prompts(self):
+ middleware = AttachingConversationKwargs()
+ req = BoltRequest(body=bot_im_message_event_body, mode="socket_mode")
+ req.context["client"] = WebClient(token="xoxb-test")
+
+ resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+
+ def test_file_share_dm_attaches_suggested_prompts(self):
+ middleware = AttachingConversationKwargs()
+ req = BoltRequest(body=file_share_im_message_event_body, mode="socket_mode")
+ req.context["client"] = WebClient(token="xoxb-test")
+
+ resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+
+ def test_app_home_opened_messages_tab_attaches_suggested_prompts(self):
+ middleware = AttachingConversationKwargs()
+ req = BoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode")
+ req.context["client"] = WebClient(token="xoxb-test")
+
+ resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+ assert "say" not in req.context
+ assert "set_title" not in req.context
+ assert "get_thread_context" not in req.context
+ assert "save_thread_context" not in req.context
+
+ def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self):
+ middleware = AttachingConversationKwargs()
+ req = BoltRequest(body=app_home_opened_home_event_body, mode="socket_mode")
+ req.context["client"] = WebClient(token="xoxb-test")
+
+ resp = middleware.process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" not in req.context
+
def test_non_assistant_event_does_not_attach_kwargs(self):
middleware = AttachingConversationKwargs()
req = BoltRequest(body=channel_user_message_event_body, mode="socket_mode")
diff --git a/tests/slack_bolt/middleware/request_verification/test_request_verification.py b/tests/slack_bolt/middleware/request_verification/test_request_verification.py
index 2c9adea43..53af43bf3 100644
--- a/tests/slack_bolt/middleware/request_verification/test_request_verification.py
+++ b/tests/slack_bolt/middleware/request_verification/test_request_verification.py
@@ -1,5 +1,6 @@
from time import time
+import pytest
from slack_sdk.signature import SignatureVerifier
from slack_bolt.middleware import RequestVerification
@@ -45,3 +46,36 @@ def test_invalid(self):
resp = middleware.process(req=req, resp=resp, next=next)
assert resp.status == 401
assert resp.body == """{"error": "invalid request"}"""
+
+ def test_ssl_check_param_requires_valid_signature(self):
+ middleware = RequestVerification(signing_secret=self.signing_secret)
+ req = BoltRequest(
+ body="token=random&ssl_check=1",
+ headers={
+ "content-type": ["application/x-www-form-urlencoded"],
+ "x-slack-signature": ["v0=invalid"],
+ "x-slack-request-timestamp": ["0"],
+ },
+ )
+ resp = BoltResponse(status=404)
+ resp = middleware.process(req=req, resp=resp, next=next)
+ assert resp.status == 401
+ assert resp.body == """{"error": "invalid request"}"""
+
+ def test_empty_signing_secret_does_not_raise_on_init(self):
+ RequestVerification(signing_secret="")
+
+ def test_socket_mode_request_skips_verification_without_signing_secret(self):
+ middleware = RequestVerification(signing_secret="")
+ req = BoltRequest(mode="socket_mode", body="payload={}", headers={})
+ resp = BoltResponse(status=404, body="default")
+ resp = middleware.process(req=req, resp=resp, next=next)
+ assert resp.status == 200
+ assert resp.body == "next"
+
+ def test_http_request_with_empty_signing_secret_raises(self):
+ middleware = RequestVerification(signing_secret="")
+ req = BoltRequest(body="payload={}", headers={})
+ resp = BoltResponse(status=404)
+ with pytest.raises(ValueError):
+ middleware.process(req=req, resp=resp, next=next)
diff --git a/tests/slack_bolt/request/test_payload_utils.py b/tests/slack_bolt/request/test_payload_utils.py
new file mode 100644
index 000000000..d58c2c436
--- /dev/null
+++ b/tests/slack_bolt/request/test_payload_utils.py
@@ -0,0 +1,408 @@
+from slack_bolt.request.payload_utils import (
+ is_event,
+ is_message_event,
+ is_any_im_message_event,
+ is_im_message_event,
+ is_assistant_event,
+ is_assistant_thread_started_event,
+ is_assistant_thread_context_changed_event,
+ is_app_home_opened_event,
+ is_user_message_event_in_assistant_thread,
+ is_bot_message_event_in_assistant_thread,
+ is_other_message_sub_event_in_assistant_thread,
+)
+from tests.scenario_tests.test_events_assistant import (
+ build_payload,
+ thread_started_event_body,
+ thread_context_changed_event_body,
+ user_message_event_body,
+ user_message_event_body_with_assistant_thread,
+ message_changed_event_body,
+ channel_user_message_event_body,
+ channel_message_changed_event_body,
+)
+from tests.scenario_tests.test_message_bot import (
+ bot_message_event_payload,
+ classic_bot_message_event_payload,
+)
+from tests.scenario_tests.test_message_deleted import event_payload as message_deleted_channel_body
+from tests.scenario_tests.test_events_ignore_self import event_body as reaction_added_event_body
+from tests.scenario_tests.test_block_actions import body as block_actions_body
+
+file_share_im_message_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "subtype": "file_share",
+ "ts": "1726133700.887259",
+ "text": "uploaded a file",
+ "files": [
+ {
+ "id": "F111",
+ "created": 1726133700,
+ "name": "test.png",
+ "title": "test.png",
+ "mimetype": "image/png",
+ "filetype": "png",
+ "user": "W222",
+ "size": 12345,
+ "mode": "hosted",
+ "is_external": False,
+ "is_public": False,
+ "url_private": "https://files.slack.com/files-pri/T111-F111/test.png",
+ "permalink": "https://example.slack.com/files/W222/F111/test.png",
+ }
+ ],
+ "upload": True,
+ "display_as_bot": False,
+ "thread_ts": "1726133698.626339",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+bot_im_thread_message_body = build_payload(
+ {
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "Here is your answer",
+ "user": "UB111",
+ "bot_id": "B111",
+ "app_id": "A222",
+ "bot_profile": {
+ "id": "B111",
+ "deleted": False,
+ "name": "assistant-app",
+ "updated": 1726133600,
+ "app_id": "A222",
+ "team_id": "T111",
+ },
+ "thread_ts": "1726133698.626339",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+im_message_no_thread_ts_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "A top-level DM, not in a thread",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+app_home_opened_messages_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "messages",
+ "event_ts": "1726133700.887259",
+ }
+)
+
+app_home_opened_home_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "home",
+ "event_ts": "1726133700.887259",
+ }
+)
+
+slash_command_body = {
+ "token": "verification_token",
+ "command": "/test",
+ "text": "hello",
+ "user_id": "U111",
+ "user_name": "primary-owner",
+ "channel_id": "C111",
+ "channel_name": "test-channel",
+ "team_id": "T111",
+ "team_domain": "test-domain",
+ "api_app_id": "A111",
+ "is_enterprise_install": "false",
+ "response_url": "https://hooks.slack.com/commands/T111/111/xxx",
+ "trigger_id": "111.222.xxx",
+}
+
+
+class TestPayloadUtils:
+ def test_is_message_event(self):
+ positives = {
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "message_changed_im": message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "message_deleted_channel": message_deleted_channel_body,
+ "file_share_im": file_share_im_message_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ }
+ negatives = {
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ "slash_command": slash_command_body,
+ "empty_dict": {},
+ }
+ for key, body in positives.items():
+ assert is_message_event(body), f"{key} should be recognized as a message event"
+ for key, body in negatives.items():
+ assert not is_message_event(body), f"{key} should NOT be recognized as a message event"
+
+ def test_is_any_im_message_event(self):
+ positives = {
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "message_changed_im": message_changed_event_body,
+ "file_share_im": file_share_im_message_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ }
+ negatives = {
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "message_deleted_channel": message_deleted_channel_body,
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ "slash_command": slash_command_body,
+ }
+ for key, body in positives.items():
+ assert is_any_im_message_event(body), f"{key} should pass {is_any_im_message_event.__name__}"
+ for key, body in negatives.items():
+ assert not is_any_im_message_event(body), f"{key} should NOT pass {is_any_im_message_event.__name__}"
+
+ def test_is_im_message_event(self):
+ # subtype must be None or "file_share" to pass
+ positives = {
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "file_share_im": file_share_im_message_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ }
+ negatives = {
+ "message_changed_im": message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "bot_message_channel": bot_message_event_payload,
+ "message_deleted_channel": message_deleted_channel_body,
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in positives.items():
+ assert is_im_message_event(body), f"{key} should pass {is_im_message_event.__name__}"
+ for key, body in negatives.items():
+ assert not is_im_message_event(body), f"{key} should NOT pass {is_im_message_event.__name__}"
+
+ def test_is_event(self):
+ positives = {
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "message_changed_im": message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "message_deleted_channel": message_deleted_channel_body,
+ "reaction_added": reaction_added_event_body,
+ "file_share_im": file_share_im_message_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ }
+ negatives = {
+ "block_actions": block_actions_body,
+ "slash_command": slash_command_body,
+ "empty_dict": {},
+ }
+ for key, body in positives.items():
+ assert is_event(body), f"{key} should be recognized as an event"
+ for key, body in negatives.items():
+ assert not is_event(body), f"{key} should NOT be recognized as an event"
+
+ def test_is_user_message_event_in_assistant_thread(self):
+ # Requires: is_im_message_event + thread_ts present + bot_id absent
+ positives = {
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "file_share_im": file_share_im_message_body,
+ }
+ negatives = {
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ "message_changed_im": message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in positives.items():
+ assert is_user_message_event_in_assistant_thread(body), (
+ f"{key} should pass {is_user_message_event_in_assistant_thread.__name__}"
+ )
+ for key, body in negatives.items():
+ assert not is_user_message_event_in_assistant_thread(body), (
+ f"{key} should NOT pass {is_user_message_event_in_assistant_thread.__name__}"
+ )
+
+ def test_is_bot_message_event_in_assistant_thread(self):
+ positives = {
+ "bot_im_thread": bot_im_thread_message_body,
+ }
+ negatives = {
+ "user_message_im": user_message_event_body,
+ "file_share_im": file_share_im_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ "message_changed_im": message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in positives.items():
+ assert is_bot_message_event_in_assistant_thread(body), (
+ f"{key} should pass {is_bot_message_event_in_assistant_thread.__name__}"
+ )
+ for key, body in negatives.items():
+ assert not is_bot_message_event_in_assistant_thread(body), (
+ f"{key} should NOT pass {is_bot_message_event_in_assistant_thread.__name__}"
+ )
+
+ def test_is_bot_message_user_message_asymmetry(self):
+ assert is_user_message_event_in_assistant_thread(file_share_im_message_body)
+ assert not is_bot_message_event_in_assistant_thread(file_share_im_message_body)
+
+ assert is_bot_message_event_in_assistant_thread(bot_im_thread_message_body)
+ assert not is_user_message_event_in_assistant_thread(bot_im_thread_message_body)
+
+ def test_is_other_message_sub_event_in_assistant_thread(self):
+ positives = {
+ "message_changed_im": message_changed_event_body,
+ }
+ negatives = {
+ "user_message_im": user_message_event_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "message_deleted_channel": message_deleted_channel_body,
+ "thread_started": thread_started_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in positives.items():
+ assert is_other_message_sub_event_in_assistant_thread(body), (
+ f"{key} should pass {is_other_message_sub_event_in_assistant_thread.__name__}"
+ )
+ for key, body in negatives.items():
+ assert not is_other_message_sub_event_in_assistant_thread(body), (
+ f"{key} should NOT pass {is_other_message_sub_event_in_assistant_thread.__name__}"
+ )
+
+ def test_is_assistant_event(self):
+ positives = {
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "user_message_im": user_message_event_body,
+ "user_message_im_with_assistant_thread": user_message_event_body_with_assistant_thread,
+ "file_share_im": file_share_im_message_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ }
+ negatives = {
+ "message_changed_im": message_changed_event_body,
+ "im_no_thread_ts": im_message_no_thread_ts_body,
+ "channel_user_message": channel_user_message_event_body,
+ "channel_message_changed": channel_message_changed_event_body,
+ "bot_message_channel": bot_message_event_payload,
+ "classic_bot_message_channel": classic_bot_message_event_payload,
+ "message_deleted_channel": message_deleted_channel_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in positives.items():
+ assert is_assistant_event(body), f"{key} should pass {is_assistant_event.__name__}"
+ for key, body in negatives.items():
+ assert not is_assistant_event(body), f"{key} should NOT pass {is_assistant_event.__name__}"
+
+ def test_is_assistant_thread_started_event(self):
+ assert is_assistant_thread_started_event(thread_started_event_body)
+
+ negatives = {
+ "thread_context_changed": thread_context_changed_event_body,
+ "user_message_im": user_message_event_body,
+ "message_changed_im": message_changed_event_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "channel_user_message": channel_user_message_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in negatives.items():
+ assert not is_assistant_thread_started_event(body), (
+ f"{key} should NOT pass {is_assistant_thread_started_event.__name__}"
+ )
+
+ def test_is_assistant_thread_context_changed_event(self):
+ assert is_assistant_thread_context_changed_event(thread_context_changed_event_body)
+
+ negatives = {
+ "thread_started": thread_started_event_body,
+ "user_message_im": user_message_event_body,
+ "message_changed_im": message_changed_event_body,
+ "bot_im_thread": bot_im_thread_message_body,
+ "channel_user_message": channel_user_message_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ }
+ for key, body in negatives.items():
+ assert not is_assistant_thread_context_changed_event(body), (
+ f"{key} should NOT pass {is_assistant_thread_context_changed_event.__name__}"
+ )
+
+ def test_is_app_home_opened_event(self):
+ assert is_app_home_opened_event(app_home_opened_messages_body)
+ assert is_app_home_opened_event(app_home_opened_home_body)
+
+ assert is_app_home_opened_event(app_home_opened_messages_body, tab="messages")
+ assert not is_app_home_opened_event(app_home_opened_home_body, tab="messages")
+
+ negatives = {
+ "thread_started": thread_started_event_body,
+ "thread_context_changed": thread_context_changed_event_body,
+ "user_message_im": user_message_event_body,
+ "channel_user_message": channel_user_message_event_body,
+ "reaction_added": reaction_added_event_body,
+ "block_actions": block_actions_body,
+ "empty_dict": {},
+ }
+ for key, body in negatives.items():
+ assert not is_app_home_opened_event(body), f"{key} should NOT pass {is_app_home_opened_event.__name__}"
+ assert not is_app_home_opened_event(body, tab="messages"), (
+ f"{key} should NOT pass {is_app_home_opened_event.__name__} with tab='messages'"
+ )
diff --git a/tests/slack_bolt_async/context/test_async_complete.py b/tests/slack_bolt_async/context/test_async_complete.py
index 4277d4218..36fa6c5a5 100644
--- a/tests/slack_bolt_async/context/test_async_complete.py
+++ b/tests/slack_bolt_async/context/test_async_complete.py
@@ -11,7 +11,6 @@
class TestAsyncComplete:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
diff --git a/tests/slack_bolt_async/context/test_async_respond.py b/tests/slack_bolt_async/context/test_async_respond.py
index b47ef1056..92d03a7f7 100644
--- a/tests/slack_bolt_async/context/test_async_respond.py
+++ b/tests/slack_bolt_async/context/test_async_respond.py
@@ -9,7 +9,6 @@
class TestAsyncRespond:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
diff --git a/tests/slack_bolt_async/context/test_async_say.py b/tests/slack_bolt_async/context/test_async_say.py
index d8d63ae8a..94ae0b159 100644
--- a/tests/slack_bolt_async/context/test_async_say.py
+++ b/tests/slack_bolt_async/context/test_async_say.py
@@ -8,7 +8,6 @@
class TestAsyncSay:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
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 016549bd6..7ac084044 100644
--- a/tests/slack_bolt_async/context/test_async_say_stream.py
+++ b/tests/slack_bolt_async/context/test_async_say_stream.py
@@ -1,28 +1,20 @@
import pytest
+from unittest.mock import patch, MagicMock
+
from slack_sdk.web.async_client import AsyncWebClient
from slack_bolt.context.say_stream.async_say_stream import AsyncSayStream
-from tests.mock_web_api_server import (
- cleanup_mock_web_api_server,
- setup_mock_web_api_server,
-)
from tests.utils import remove_os_env_temporarily, restore_os_env
class TestAsyncSayStream:
- default_chat_stream_buffer_size = AsyncWebClient.chat_stream.__kwdefaults__["buffer_size"]
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
- setup_mock_web_api_server(self)
- valid_token = "xoxb-valid"
- mock_api_server_base_url = "http://localhost:8888"
try:
- self.web_client = AsyncWebClient(token=valid_token, base_url=mock_api_server_base_url)
- yield # run the test here
+ self.web_client = AsyncWebClient(token="xoxb-valid")
+ yield
finally:
- cleanup_mock_web_api_server(self)
restore_os_env(old_os_env)
@pytest.mark.asyncio
@@ -46,16 +38,22 @@ async def test_default_params(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = await say_stream()
+ mock_chat_stream = MagicMock()
- assert stream._buffer_size == self.default_chat_stream_buffer_size
- assert stream._stream_args == {
- "channel": "C111",
- "thread_ts": "111.222",
- "recipient_team_id": "T111",
- "recipient_user_id": "U111",
- "task_display_mode": None,
- }
+ async def fake_chat_stream(**kwargs):
+ return mock_chat_stream(**kwargs)
+
+ with patch.object(self.web_client, "chat_stream", side_effect=fake_chat_stream):
+ await say_stream()
+ mock_chat_stream.assert_called_once_with(
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
@pytest.mark.asyncio
async def test_parameter_overrides(self):
@@ -66,16 +64,22 @@ async def test_parameter_overrides(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = await say_stream(channel="C222", thread_ts="333.444", recipient_team_id="T222", recipient_user_id="U222")
+ mock_chat_stream = MagicMock()
- assert stream._buffer_size == self.default_chat_stream_buffer_size
- assert stream._stream_args == {
- "channel": "C222",
- "thread_ts": "333.444",
- "recipient_team_id": "T222",
- "recipient_user_id": "U222",
- "task_display_mode": None,
- }
+ async def fake_chat_stream(**kwargs):
+ return mock_chat_stream(**kwargs)
+
+ with patch.object(self.web_client, "chat_stream", side_effect=fake_chat_stream):
+ await say_stream(channel="C222", thread_ts="333.444", recipient_team_id="T222", recipient_user_id="U222")
+ mock_chat_stream.assert_called_once_with(
+ channel="C222",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ thread_ts="333.444",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
@pytest.mark.asyncio
async def test_buffer_size_overrides(self):
@@ -86,19 +90,52 @@ async def test_buffer_size_overrides(self):
recipient_user_id="U111",
thread_ts="111.222",
)
- stream = await say_stream(
- buffer_size=100,
- channel="C222",
- thread_ts="333.444",
- recipient_team_id="T222",
- recipient_user_id="U222",
+ mock_chat_stream = MagicMock()
+
+ async def fake_chat_stream(**kwargs):
+ return mock_chat_stream(**kwargs)
+
+ with patch.object(self.web_client, "chat_stream", side_effect=fake_chat_stream):
+ await say_stream(
+ buffer_size=100,
+ channel="C222",
+ thread_ts="333.444",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ )
+ mock_chat_stream.assert_called_once_with(
+ buffer_size=100,
+ channel="C222",
+ recipient_team_id="T222",
+ recipient_user_id="U222",
+ thread_ts="333.444",
+ icon_emoji=None,
+ icon_url=None,
+ username=None,
+ )
+
+ @pytest.mark.asyncio
+ async def test_authorship_overrides(self):
+ say_stream = AsyncSayStream(
+ client=self.web_client,
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
)
+ mock_chat_stream = MagicMock()
+
+ async def fake_chat_stream(**kwargs):
+ return mock_chat_stream(**kwargs)
- assert stream._buffer_size == 100
- assert stream._stream_args == {
- "channel": "C222",
- "thread_ts": "333.444",
- "recipient_team_id": "T222",
- "recipient_user_id": "U222",
- "task_display_mode": None,
- }
+ with patch.object(self.web_client, "chat_stream", side_effect=fake_chat_stream):
+ await say_stream(icon_emoji=":maple_leaf:", username="Charlie Brown")
+ mock_chat_stream.assert_called_once_with(
+ channel="C111",
+ recipient_team_id="T111",
+ recipient_user_id="U111",
+ thread_ts="111.222",
+ icon_emoji=":maple_leaf:",
+ icon_url=None,
+ username="Charlie Brown",
+ )
diff --git a/tests/slack_bolt_async/context/test_async_set_status.py b/tests/slack_bolt_async/context/test_async_set_status.py
index e785ff89e..95e009004 100644
--- a/tests/slack_bolt_async/context/test_async_set_status.py
+++ b/tests/slack_bolt_async/context/test_async_set_status.py
@@ -8,7 +8,6 @@
class TestAsyncSetStatus:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
@@ -40,6 +39,16 @@ async def test_set_status_loading_messages(self):
)
assert response.status_code == 200
+ @pytest.mark.asyncio
+ async def test_set_status_authorship(self):
+ set_status = AsyncSetStatus(client=self.web_client, channel_id="C111", thread_ts="123.123")
+ response: AsyncSlackResponse = await set_status(
+ status="Thinking...",
+ icon_emoji=":maple_leaf:",
+ username="Charlie Brown",
+ )
+ assert response.status_code == 200
+
@pytest.mark.asyncio
async def test_set_status_invalid(self):
set_status = AsyncSetStatus(client=self.web_client, channel_id="C111", thread_ts="123.123")
diff --git a/tests/slack_bolt_async/context/test_async_set_suggested_prompts.py b/tests/slack_bolt_async/context/test_async_set_suggested_prompts.py
index 2a09434a8..a881d7abd 100644
--- a/tests/slack_bolt_async/context/test_async_set_suggested_prompts.py
+++ b/tests/slack_bolt_async/context/test_async_set_suggested_prompts.py
@@ -1,4 +1,5 @@
import asyncio
+from unittest.mock import MagicMock, patch
import pytest
from slack_sdk.web.async_client import AsyncWebClient
@@ -10,7 +11,6 @@
class TestAsyncSetSuggestedPrompts:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
@@ -41,6 +41,65 @@ async def test_set_suggested_prompts_objects(self):
)
assert response.status_code == 200
+ @pytest.mark.asyncio
+ async def test_set_suggested_prompts_without_thread_ts(self):
+ set_suggested_prompts = AsyncSetSuggestedPrompts(client=self.web_client, channel_id="C111")
+ mock_api = MagicMock()
+
+ async def fake_api(**kwargs):
+ return mock_api(**kwargs)
+
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, side_effect=fake_api
+ ):
+ await set_suggested_prompts(prompts=["One", "Two"])
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts=None,
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
+ @pytest.mark.asyncio
+ async def test_set_suggested_prompts_thread_ts_override(self):
+ # The call-time thread_ts must win over the stored one
+ set_suggested_prompts = AsyncSetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="999.999")
+ mock_api = MagicMock()
+
+ async def fake_api(**kwargs):
+ return mock_api(**kwargs)
+
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, side_effect=fake_api
+ ):
+ await set_suggested_prompts(prompts=["One", "Two"], thread_ts="123.123")
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts="123.123",
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
+ @pytest.mark.asyncio
+ async def test_set_suggested_prompts_thread_ts_override_falsy(self):
+ # An explicitly passed falsy thread_ts must be forwarded, not swallowed by the stored value
+ set_suggested_prompts = AsyncSetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="123.123")
+ mock_api = MagicMock()
+
+ async def fake_api(**kwargs):
+ return mock_api(**kwargs)
+
+ with patch.object(
+ self.web_client, self.web_client.assistant_threads_setSuggestedPrompts.__name__, side_effect=fake_api
+ ):
+ await set_suggested_prompts(prompts=["One", "Two"], thread_ts="")
+ mock_api.assert_called_once_with(
+ channel_id="C111",
+ thread_ts="",
+ prompts=[{"title": "One", "message": "One"}, {"title": "Two", "message": "Two"}],
+ title=None,
+ )
+
@pytest.mark.asyncio
async def test_set_suggested_prompts_invalid(self):
set_suggested_prompts = AsyncSetSuggestedPrompts(client=self.web_client, channel_id="C111", thread_ts="123.123")
diff --git a/tests/slack_bolt_async/logger/test_unmatched_suggestions.py b/tests/slack_bolt_async/logger/test_unmatched_suggestions.py
index d8c659892..93343c4a2 100644
--- a/tests/slack_bolt_async/logger/test_unmatched_suggestions.py
+++ b/tests/slack_bolt_async/logger/test_unmatched_suggestions.py
@@ -22,7 +22,8 @@ def test_block_actions(self):
"block_id": "b",
"action_id": "action-id-value",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -30,7 +31,9 @@ def test_block_actions(self):
async def handle_some_action(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_attachment_actions(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=attachment_actions, mode="socket_mode")
@@ -46,7 +49,8 @@ def test_attachment_actions(self):
}
],
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -54,7 +58,9 @@ def test_attachment_actions(self):
async def handle_some_action(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_app_mention_event(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=app_mention_event, mode="socket_mode")
@@ -63,14 +69,17 @@ def test_app_mention_event(self):
"event": {"type": "app_mention"},
}
message = warning_unhandled_request(req)
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.event("app_mention")
async def handle_app_mention_events(body, logger):
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_function_event(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=function_event, mode="socket_mode")
@@ -79,7 +88,8 @@ def test_function_event(self):
"event": {"type": "function_executed"},
}
message = warning_unhandled_request(req)
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -94,7 +104,9 @@ async def handle_some_function(ack, body, complete, fail, logger):
except Exception as e:
error = f"Failed to handle a function request (error: {{e}})"
await fail(error=error)
-""" == message
+"""
+ == message
+ )
def test_commands(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=slash_command, mode="socket_mode")
@@ -103,7 +115,8 @@ def test_commands(self):
"type": None,
"command": "/start-conv",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -111,7 +124,9 @@ def test_commands(self):
async def handle_some_command(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_shortcut(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=global_shortcut, mode="socket_mode")
@@ -120,7 +135,8 @@ def test_shortcut(self):
"type": "shortcut",
"callback_id": "test-shortcut",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -128,7 +144,9 @@ def test_shortcut(self):
async def handle_shortcuts(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
req: AsyncBoltRequest = AsyncBoltRequest(body=message_shortcut, mode="socket_mode")
message = warning_unhandled_request(req)
@@ -136,7 +154,8 @@ async def handle_shortcuts(ack, body, logger):
"type": "message_action",
"callback_id": "test-shortcut",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -144,7 +163,9 @@ async def handle_shortcuts(ack, body, logger):
async def handle_shortcuts(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_view(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=view_submission, mode="socket_mode")
@@ -153,7 +174,8 @@ def test_view(self):
"type": "view_submission",
"view": {"type": "modal", "callback_id": "view-id"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -161,7 +183,9 @@ def test_view(self):
async def handle_view_submission_events(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
req: AsyncBoltRequest = AsyncBoltRequest(body=view_closed, mode="socket_mode")
message = warning_unhandled_request(req)
@@ -169,7 +193,8 @@ async def handle_view_submission_events(ack, body, logger):
"type": "view_closed",
"view": {"type": "modal", "callback_id": "view-id"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -177,7 +202,9 @@ async def handle_view_submission_events(ack, body, logger):
async def handle_view_closed_events(ack, body, logger):
await ack()
logger.info(body)
-""" == message
+"""
+ == message
+ )
def test_block_suggestion(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=block_suggestion, mode="socket_mode")
@@ -189,14 +216,17 @@ def test_block_suggestion(self):
"action_id": "the-id",
"value": "search word",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.options("the-id")
async def handle_some_options(ack):
await ack(options=[ ... ])
-""" == message
+"""
+ == message
+ )
def test_dialog_suggestion(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=dialog_suggestion, mode="socket_mode")
@@ -206,14 +236,17 @@ def test_dialog_suggestion(self):
"callback_id": "the-id",
"value": "search keyword",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@app.options({{"type": "dialog_suggestion", "callback_id": "the-id"}})
async def handle_some_options(ack):
await ack(options=[ ... ])
-""" == message
+"""
+ == message
+ )
def test_step(self):
req: AsyncBoltRequest = AsyncBoltRequest(body=step_edit_payload, mode="socket_mode")
@@ -222,7 +255,8 @@ def test_step(self):
"type": "workflow_step_edit",
"callback_id": "copy_review",
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -235,14 +269,17 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
req: AsyncBoltRequest = AsyncBoltRequest(body=step_save_payload, mode="socket_mode")
message = warning_unhandled_request(req)
filtered_body = {
"type": "view_submission",
"view": {"type": "workflow_step", "callback_id": "copy_review"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -255,14 +292,17 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
req: AsyncBoltRequest = AsyncBoltRequest(body=step_execute_payload, mode="socket_mode")
message = warning_unhandled_request(req)
filtered_body = {
"type": "event_callback",
"event": {"type": "workflow_step_execute"},
}
- assert f"""Unhandled request ({filtered_body})
+ assert (
+ f"""Unhandled request ({filtered_body})
---
[Suggestion] You can handle this type of event with the following listener function:
@@ -275,7 +315,9 @@ def test_step(self):
)
# Pass Step to set up listeners
app.step(ws)
-""" == message
+"""
+ == message
+ )
block_actions = {
diff --git a/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py b/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py
index a00b35cd3..c7da4ce93 100644
--- a/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py
+++ b/tests/slack_bolt_async/middleware/attaching_conversation_kwargs/test_async_attaching_conversation_kwargs.py
@@ -7,6 +7,7 @@
from slack_bolt.request.async_request import AsyncBoltRequest
from slack_bolt.response import BoltResponse
from tests.scenario_tests_async.test_events_assistant import (
+ build_payload,
thread_started_event_body,
user_message_event_body,
channel_user_message_event_body,
@@ -19,6 +20,70 @@ async def next():
ASSISTANT_KWARGS = ("say", "set_title", "set_suggested_prompts", "get_thread_context", "save_thread_context")
+# A top-level DM (not in a thread) is not an assistant thread, but set_suggested_prompts is still attached.
+top_level_im_message_event_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "A top-level DM, not in a thread",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# A bot-authored top-level DM is also in scope: set_suggested_prompts is attached for any IM message.
+bot_im_message_event_body = build_payload(
+ {
+ "type": "message",
+ "ts": "1726133700.887259",
+ "text": "A DM authored by a bot",
+ "user": "UB111",
+ "bot_id": "B111",
+ "app_id": "A222",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# A file_share DM is in scope too (subtype "file_share" passes is_im_message_event).
+file_share_im_message_event_body = build_payload(
+ {
+ "user": "W222",
+ "type": "message",
+ "subtype": "file_share",
+ "ts": "1726133700.887259",
+ "text": "uploaded a file",
+ "channel": "D111",
+ "event_ts": "1726133700.887259",
+ "channel_type": "im",
+ }
+)
+
+# Opening the Messages tab of App Home is in scope for set_suggested_prompts.
+app_home_opened_messages_event_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "messages",
+ "event_ts": "1726133700.887259",
+ }
+)
+
+# Opening the Home tab is NOT in scope: set_suggested_prompts should not be attached.
+app_home_opened_home_event_body = build_payload(
+ {
+ "type": "app_home_opened",
+ "user": "W222",
+ "channel": "D111",
+ "tab": "home",
+ "event_ts": "1726133700.887259",
+ }
+)
+
class TestAsyncAttachingConversationKwargs:
@pytest.mark.asyncio
@@ -51,6 +116,71 @@ async def test_user_message_event_attaches_kwargs(self):
assert "say_stream" in req.context
assert "set_status" in req.context
+ @pytest.mark.asyncio
+ async def test_top_level_dm_attaches_suggested_prompts_but_not_set_title(self):
+ middleware = AsyncAttachingConversationKwargs()
+ req = AsyncBoltRequest(body=top_level_im_message_event_body, mode="socket_mode")
+ req.context["client"] = AsyncWebClient(token="xoxb-test")
+
+ resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+ assert "set_title" not in req.context
+ assert "say" not in req.context
+ assert "get_thread_context" not in req.context
+ assert "save_thread_context" not in req.context
+ assert "say_stream" in req.context
+ assert "set_status" in req.context
+
+ @pytest.mark.asyncio
+ async def test_bot_dm_attaches_suggested_prompts(self):
+ middleware = AsyncAttachingConversationKwargs()
+ req = AsyncBoltRequest(body=bot_im_message_event_body, mode="socket_mode")
+ req.context["client"] = AsyncWebClient(token="xoxb-test")
+
+ resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+
+ @pytest.mark.asyncio
+ async def test_file_share_dm_attaches_suggested_prompts(self):
+ middleware = AsyncAttachingConversationKwargs()
+ req = AsyncBoltRequest(body=file_share_im_message_event_body, mode="socket_mode")
+ req.context["client"] = AsyncWebClient(token="xoxb-test")
+
+ resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+
+ @pytest.mark.asyncio
+ async def test_app_home_opened_messages_tab_attaches_suggested_prompts(self):
+ middleware = AsyncAttachingConversationKwargs()
+ req = AsyncBoltRequest(body=app_home_opened_messages_event_body, mode="socket_mode")
+ req.context["client"] = AsyncWebClient(token="xoxb-test")
+
+ resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" in req.context
+ assert "say" not in req.context
+ assert "set_title" not in req.context
+ assert "get_thread_context" not in req.context
+ assert "save_thread_context" not in req.context
+
+ @pytest.mark.asyncio
+ async def test_app_home_opened_home_tab_does_not_attach_suggested_prompts(self):
+ middleware = AsyncAttachingConversationKwargs()
+ req = AsyncBoltRequest(body=app_home_opened_home_event_body, mode="socket_mode")
+ req.context["client"] = AsyncWebClient(token="xoxb-test")
+
+ resp = await middleware.async_process(req=req, resp=BoltResponse(status=404), next=next)
+
+ assert resp.status == 200
+ assert "set_suggested_prompts" not in req.context
+
@pytest.mark.asyncio
async def test_non_assistant_event_does_not_attach_kwargs(self):
middleware = AsyncAttachingConversationKwargs()
diff --git a/tests/slack_bolt_async/middleware/authorization/test_single_team_authorization.py b/tests/slack_bolt_async/middleware/authorization/test_single_team_authorization.py
index 0ddb6281d..ab30130d0 100644
--- a/tests/slack_bolt_async/middleware/authorization/test_single_team_authorization.py
+++ b/tests/slack_bolt_async/middleware/authorization/test_single_team_authorization.py
@@ -19,7 +19,6 @@ async def next():
class TestSingleTeamAuthorization:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
diff --git a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py
index c097dd146..126b04f94 100644
--- a/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py
+++ b/tests/slack_bolt_async/middleware/request_verification/test_request_verification.py
@@ -50,3 +50,39 @@ async def test_invalid(self):
resp = await middleware.async_process(req=req, resp=resp, next=next)
assert resp.status == 401
assert resp.body == """{"error": "invalid request"}"""
+
+ @pytest.mark.asyncio
+ async def test_ssl_check_param_requires_valid_signature(self):
+ middleware = AsyncRequestVerification(signing_secret="secret")
+ req = AsyncBoltRequest(
+ body="token=random&ssl_check=1",
+ headers={
+ "content-type": ["application/x-www-form-urlencoded"],
+ "x-slack-signature": ["v0=invalid"],
+ "x-slack-request-timestamp": ["0"],
+ },
+ )
+ resp = BoltResponse(status=404)
+ resp = await middleware.async_process(req=req, resp=resp, next=next)
+ assert resp.status == 401
+ assert resp.body == """{"error": "invalid request"}"""
+
+ def test_empty_signing_secret_does_not_raise_on_init(self):
+ AsyncRequestVerification(signing_secret="")
+
+ @pytest.mark.asyncio
+ async def test_socket_mode_request_skips_verification_without_signing_secret(self):
+ middleware = AsyncRequestVerification(signing_secret="")
+ req = AsyncBoltRequest(mode="socket_mode", body="payload={}", headers={})
+ resp = BoltResponse(status=404, body="default")
+ resp = await middleware.async_process(req=req, resp=resp, next=next)
+ assert resp.status == 200
+ assert resp.body == "next"
+
+ @pytest.mark.asyncio
+ async def test_http_request_with_empty_signing_secret_raises(self):
+ middleware = AsyncRequestVerification(signing_secret="")
+ req = AsyncBoltRequest(body="payload={}", headers={})
+ resp = BoltResponse(status=404)
+ with pytest.raises(ValueError):
+ await middleware.async_process(req=req, resp=resp, next=next)
diff --git a/tests/slack_bolt_async/oauth/test_async_oauth_flow.py b/tests/slack_bolt_async/oauth/test_async_oauth_flow.py
index 5714e1a6a..538861c05 100644
--- a/tests/slack_bolt_async/oauth/test_async_oauth_flow.py
+++ b/tests/slack_bolt_async/oauth/test_async_oauth_flow.py
@@ -30,7 +30,6 @@
class TestAsyncOAuthFlow:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
old_os_env = remove_os_env_temporarily()
diff --git a/tests/slack_bolt_async/oauth/test_async_oauth_flow_sqlite3.py b/tests/slack_bolt_async/oauth/test_async_oauth_flow_sqlite3.py
index 00300929f..098e531b7 100644
--- a/tests/slack_bolt_async/oauth/test_async_oauth_flow_sqlite3.py
+++ b/tests/slack_bolt_async/oauth/test_async_oauth_flow_sqlite3.py
@@ -16,7 +16,6 @@
class TestAsyncOAuthFlowSQLite3:
-
@pytest.fixture(scope="function", autouse=True)
def setup_teardown(self):
setup_mock_web_api_server_async(self)
@@ -41,6 +40,18 @@ async def test_instantiation(self):
assert oauth_flow.logger is not None
assert oauth_flow.client is not None
+ @pytest.mark.asyncio
+ async def test_instantiation_token_rotation_expiration_minutes(self):
+ oauth_flow = AsyncOAuthFlow.sqlite3(
+ database="./logs/test_db",
+ client_id="111.222",
+ client_secret="xxx",
+ scopes=["chat:write", "commands"],
+ token_rotation_expiration_minutes=30,
+ )
+ assert oauth_flow.settings.token_rotation_expiration_minutes == 30
+ assert oauth_flow.settings.authorize.token_rotation_expiration_minutes == 30
+
@pytest.mark.asyncio
async def test_handle_installation(self):
oauth_flow = AsyncOAuthFlow.sqlite3(