### Setup Local Project and Dependencies Source: https://github.com/slackapi/bolt-python/blob/main/examples/getting_started/README.md Clone the Bolt for Python repository, navigate to the example directory, set up a virtual environment, and install project dependencies using pip. ```zsh git clone https://github.com/slackapi/bolt-python.git cd bolt-python/examples/getting_started/ python3 -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Setup Virtual Environment and Install Dependencies Source: https://github.com/slackapi/bolt-python/blob/main/docs/english/tutorial/order-confirmation/order-confirmation.md Commands to set up a Python virtual environment, activate it, and install project dependencies from requirements.txt. ```bash python -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Initialize App with InstallationStore and OAuthFlow Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/app.html Initialize the App with an InstallationStore and an OAuthFlow. This setup is used for handling OAuth installations and retrieving installation data. ```python from slack_bolt.oauth.oauth_flow import OAuthFlow from slack_sdk.oauth.installation_store import FileInstallationStore from slack_bolt import App installation_store = FileInstallationStore() os_settings = { "client_id": os.environ.get("SLACK_CLIENT_ID"), "client_secret": os.environ.get("SLACK_CLIENT_SECRET"), "scopes": ["chat:write", "commands"], } os_flow = OAuthFlow(settings=os_settings, installation_store=installation_store) app = App(installation_store=installation_store, oauth_flow=os_flow) ``` -------------------------------- ### Run All Setup and Tests Source: https://github.com/slackapi/bolt-python/blob/main/AGENTS.md A convenience script to install all dependencies, format, lint, run tests, and perform type checking. ```bash ./scripts/install_all_and_run_tests.sh ``` -------------------------------- ### GET /slack/install and GET /slack/redirect Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/index.html Handles GET requests for the OAuth installation flow. It manages both the initial installation path and the redirect URI callback. ```APIDOC ## GET /slack/install and GET /slack/redirect ### Description Handles GET requests for the OAuth installation flow. It manages both the initial installation path and the redirect URI callback. ### Method GET ### Endpoint /slack/install /slack/redirect ### Parameters #### Query Parameters - **code** (string) - Required - The authorization code received from Slack. - **state** (string) - Optional - The state parameter for CSRF protection. ### Response #### Success Response (200) - Upon successful installation or callback, a redirect or success message is provided. #### Response Example ```json { "example": "response body" } ``` ``` -------------------------------- ### start Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/index.html Starts a web server for local development. ```APIDOC ## start ### Description Starts a web server for local development. This method internally starts a Web server process built with the `http.server` module. For production, consider using a production-ready WSGI server such as Gunicorn. ### Method Signature `def start(self, port: int = 3000, path: str = '/slack/events', http_server_logger_enabled: bool = True) -> None` ### Parameters #### `port` - **Type**: `int` - **Description**: The port to listen on. Defaults to 3000. #### `path` - **Type**: `str` - **Description**: The path to handle request from Slack. Defaults to `/slack/events`. #### `http_server_logger_enabled` - **Type**: `bool` - **Description**: The flag to enable http.server logging if True. Defaults to True. ### Usage Example ```python # With the default settings, `http://localhost:3000/slack/events` # is available for handling incoming requests from Slack app.start() ``` ``` -------------------------------- ### GET /slack/install and /slack/oauth_redirect Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/tornado/handler.html Handles Slack OAuth installation and callback flows using the configured OAuthFlow instance. ```APIDOC ## GET /slack/install ### Description Initiates the Slack OAuth installation flow. ### Method GET ### Endpoint /slack/install ## GET /slack/oauth_redirect ### Description Handles the OAuth callback redirect from Slack. ### Method GET ### Endpoint /slack/oauth_redirect ``` -------------------------------- ### Start the Application Source: https://github.com/slackapi/bolt-python/blob/main/docs/english/tutorial/modals/modals.md Execute the Python script to start the local server. ```bash # Start your local server python3 simple_modal_example.py ``` -------------------------------- ### Get or create default installation store Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/async_internals.html Retrieves an existing FileInstallationStore for the given client ID or creates a new one if it does not exist. ```python def get_or_create_default_installation_store(client_id: str) -> AsyncInstallationStore: store = default_installation_stores.get(client_id) if store is None: store = FileInstallationStore(client_id=client_id) default_installation_stores[client_id] = store return store ``` -------------------------------- ### Handle installation requests Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/index.html Manages the installation request by building the authorization URL and rendering the install page or redirecting. ```python def handle_installation(self, request: BoltRequest) -> BoltResponse: set_cookie_value: Optional[str] = None url = self.build_authorize_url("", request) if self.settings.state_validation_enabled is True: state = self.issue_new_state(request) url = self.build_authorize_url(state, request) set_cookie_value = self.settings.state_utils.build_set_cookie_for_new_state(state) if self.settings.install_page_rendering_enabled: html = self.build_install_page_html(url, request) return BoltResponse( status=200, body=html, headers=self.append_set_cookie_headers( {"Content-Type": "text/html; charset=utf-8"}, set_cookie_value, ), ) else: return BoltResponse( status=302, body="", headers=self.append_set_cookie_headers( {"Content-Type": "text/html; charset=utf-8", "Location": url}, set_cookie_value, ), ) ``` -------------------------------- ### Start a Local Development Server Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/index.html Start a web server for local development using the `start` method. This method listens for incoming requests from Slack on a specified port and path. ```python app.start() ``` -------------------------------- ### Handle Installation Data Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/index.html Constructs an Installation object from OAuth response data and saves it using the configured installation store. ```python enterprise_url = auth_test.get("url") return Installation( app_id=oauth_response.get("app_id"), enterprise_id=installed_enterprise.get("id"), enterprise_name=installed_enterprise.get("name"), enterprise_url=enterprise_url, team_id=installed_team.get("id"), team_name=installed_team.get("name"), bot_token=bot_token, bot_id=bot_id, bot_user_id=oauth_response.get("bot_user_id"), bot_scopes=oauth_response.get("scope"), # type: ignore[arg-type] # comma-separated string bot_refresh_token=oauth_response.get("refresh_token"), # since v1.7 bot_token_expires_in=oauth_response.get("expires_in"), # since v1.7 user_id=installer.get("id"), # type: ignore[arg-type] user_token=installer.get("access_token"), user_scopes=installer.get("scope"), # type: ignore[arg-type] # comma-separated string user_refresh_token=installer.get("refresh_token"), # since v1.7 user_token_expires_in=installer.get("expires_in"), # type: ignore[arg-type] # since v1.7 incoming_webhook_url=incoming_webhook.get("url"), incoming_webhook_channel=incoming_webhook.get("channel"), incoming_webhook_channel_id=incoming_webhook.get("channel_id"), incoming_webhook_configuration_url=incoming_webhook.get("configuration_url"), is_enterprise_install=is_enterprise_install, token_type=oauth_response.get("token_type"), ) except SlackApiError as e: message = f"Failed to fetch oauth.v2.access result with code: {code} - error: {e}" self.logger.warning(message) return None def store_installation(self, request: BoltRequest, installation: Installation): # may raise BoltError self.settings.installation_store.save(installation) ``` -------------------------------- ### Store Installation Asynchronously Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/async_oauth_flow.html Saves the installation data to the configured store. ```python async def store_installation(self, request: AsyncBoltRequest, installation: Installation): # may raise BoltError await self.settings.installation_store.async_save(installation) ``` -------------------------------- ### Initialize App with Custom Installation Store Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/app.html Initialize the App with a custom installation store for managing OAuth installations. This is useful for storing installation data in a database. ```python from slack_bolt import App from slack_sdk.oauth.installation_store import FileInstallationStore installation_store = FileInstallationStore() app = App( token="xoxb-your-user-token", signing_secret="your-signing-secret", client_id="your-client-id", client_secret="your-client-secret", installation_store=installation_store ) ``` -------------------------------- ### Start Server Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_app.html Starts the asynchronous web server using aiohttp. ```APIDOC ## POST /start ### Description Starts the asynchronous web server using aiohttp to handle incoming Slack events. ### Method POST ### Endpoint /start ### Parameters #### Query Parameters - **port** (int) - Optional - The port to listen on (Default: 3000) - **path** (str) - Optional - The path to handle request from Slack (Default: `/slack/events`) - **host** (str) - Optional - The hostname to serve the web endpoints. (Default: 0.0.0.0) ### Request Example ```json { "example": "No request body needed to start the server" } ``` ### Response #### Success Response (200) - **None** - The server starts and runs in the background. #### Response Example ```json { "example": "No response body, server starts execution." } ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/slackapi/bolt-python/blob/main/docs/english/tutorial/modals/modals.md Install the necessary packages listed in the requirements.txt file. ```bash # Install the dependencies pip install -r requirements.txt ``` -------------------------------- ### Handle Slack App Installation Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/async_oauth_flow.html Handles the installation flow for a Slack app, building authorization URLs and rendering an installation page or redirecting the user. ```python async def handle_installation(self, request: AsyncBoltRequest) -> BoltResponse: set_cookie_value: Optional[str] = None url = await self.build_authorize_url("", request) if self.settings.state_validation_enabled is True: state = await self.issue_new_state(request) url = await self.build_authorize_url(state, request) set_cookie_value = self.settings.state_utils.build_set_cookie_for_new_state(state) if self.settings.install_page_rendering_enabled: html = await self.build_install_page_html(url, request) return BoltResponse( status=200, body=html, headers=await self.append_set_cookie_headers( {"Content-Type": "text/html; charset=utf-8"}, set_cookie_value, ), ) else: return BoltResponse( status=302, body="", headers=await self.append_set_cookie_headers( {"Content-Type": "text/html; charset=utf-8", "Location": url}, set_cookie_value, ), ) ``` -------------------------------- ### Server Start Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_server.html Starts the web server process. ```APIDOC ## start ### Description Starts a new web server process using the configured host and port. ### Parameters #### Query Parameters - **host** (str) - Optional - The host address to bind the server to. ``` -------------------------------- ### AsyncOAuthFlow.store_installation Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/async_oauth_flow.html Saves the installation details to the configured installation store. ```APIDOC ## POST /store_installation ### Description Saves the provided installation object to the configured installation store asynchronously. ### Method POST ### Parameters #### Request Body - **request** (AsyncBoltRequest) - Required - The incoming asynchronous bolt request. - **installation** (Installation) - Required - The installation object containing bot and user tokens, scopes, and webhook information. ``` -------------------------------- ### Store Installation Details Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/oauth_flow.html Saves the installation details using the configured installation store. This method may raise a BoltError. ```python def store_installation(self, request: BoltRequest, installation: Installation): # may raise BoltError self.settings.installation_store.save(installation) ``` -------------------------------- ### handle_installation Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/async_oauth_flow.html Handles the initial installation request, builds the authorization URL, and returns either an HTML install page or a redirect response. ```APIDOC ## handle_installation ### Description Handles the Slack app installation request. It builds the authorization URL, optionally performs state validation, and returns a BoltResponse containing either the rendered install page or a redirect to the Slack authorization URL. ### Method async ### Parameters #### Request Body - **request** (AsyncBoltRequest) - Required - The incoming asynchronous Bolt request object. ### Response #### Success Response (200/302) - **BoltResponse** (object) - Returns a response with status 200 (HTML page) or 302 (Redirect). ``` -------------------------------- ### store_installation Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/oauth_flow.html Saves the installation details to the configured installation store. ```APIDOC ## store_installation ### Description Saves the provided installation object to the configured installation store. This method may raise a BoltError if the save operation fails. ### Parameters #### Request Body - **request** (BoltRequest) - Required - The incoming Bolt request object. - **installation** (Installation) - Required - The installation data to be persisted. ``` -------------------------------- ### GET OAuth Installation Handler Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_server.html Handles GET requests for the Slack OAuth installation flow. ```APIDOC ## GET [install_path] ### Description Handles the initial installation request for the Slack OAuth flow. ### Method GET ### Endpoint [install_path] ``` -------------------------------- ### handle_installation Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/index.html Handles the initial installation request, building the authorization URL and returning either an HTML install page or a redirect response. ```APIDOC ## handle_installation ### Description Processes an incoming installation request. It builds the Slack authorization URL, optionally performs state validation, and returns a response that either renders an install page or redirects the user to Slack. ### Parameters #### Request Body - **request** (BoltRequest) - Required - The incoming Bolt request object. ### Response #### Success Response (200/302) - **BoltResponse** - The response object containing either the HTML body or a redirect location header. ``` -------------------------------- ### Handle GET requests for SlackOAuthHandler Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/tornado/handler.html Handles GET requests for the OAuth flow, including installation and redirect URI callbacks. It checks the request path against the configured install and redirect paths. ```python def get(self): if self.app.oauth_flow is not None: oauth_flow: OAuthFlow = self.app.oauth_flow if self.request.path == oauth_flow.install_path: bolt_resp = oauth_flow.handle_installation(to_bolt_request(self.request)) set_response(self, bolt_resp) return elif self.request.path == oauth_flow.redirect_uri_path: bolt_resp = oauth_flow.handle_callback(to_bolt_request(self.request)) set_response(self, bolt_resp) return self.set_status(404) ``` -------------------------------- ### start() Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/index.html Starts a web server for local development, useful for testing your Slack app. ```APIDOC ## start() ### Description Starts a web server for local development. This is useful for testing your Slack app without deploying it. ### Method Signature `start(port: int = 3000, path: str = "/slack/events", http_server_logger_enabled: bool = True) -> None` ### Parameters - **port** (int) - Optional - The port number to listen on. Defaults to 3000. - **path** (str) - Optional - The URL path to handle incoming requests from Slack. Defaults to `/slack/events`. - **http_server_logger_enabled** (bool) - Optional - Flag to enable logging for the HTTP server. Defaults to True. ### Usage Example ```python app.start() ``` ### Notes For production environments, it is recommended to use a production-ready WSGI server like Gunicorn. ``` -------------------------------- ### GET Request Handler Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_server.html Handles incoming GET requests for OAuth installation and callback flows. ```APIDOC ## GET [install_path] or [redirect_uri_path] ### Description Handles OAuth installation and callback requests based on the configured OAuth flow paths. ### Method GET ### Endpoint Defined by oauth_flow.install_path or oauth_flow.redirect_uri_path ### Response #### Success Response (200) - **response** (aiohttp.web_response.Response) - The response generated by the OAuth flow handler. ``` -------------------------------- ### Handle Installation Request Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/oauth_flow.html This method handles the initial installation request from Slack, building the authorization URL and optionally generating a state parameter for security. ```APIDOC ## POST /slack/install ### Description Handles the initial installation request from Slack. It constructs the authorization URL and can generate a state parameter for security if state validation is enabled. It then renders an HTML page for installation or redirects the user. ### Method POST ### Endpoint /slack/install ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Implicitly handled by the framework) ### Request Example None ### Response #### Success Response (200) - **body** (text/html) - HTML content for the installation page. - **headers** (dict) - Includes 'Content-Type' and potentially 'Set-Cookie' if state is generated. #### Success Response (302) - **headers** (dict) - Includes 'Location' header with the authorization URL and 'Set-Cookie' if state is generated. #### Response Example ```json { "status": 200, "body": "...installation page HTML...", "headers": { "Content-Type": "text/html; charset=utf-8", "Set-Cookie": "slack-state=..." } } ``` ```json { "status": 302, "body": "", "headers": { "Content-Type": "text/html; charset=utf-8", "Location": "https://slack.com/oauth/v2/authorize?...", "Set-Cookie": "slack-state=..." } } ``` ``` -------------------------------- ### SlackOAuthHandler GET Method Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/tornado/handler.html Handles GET requests for the Slack OAuth flow, managing installation and redirect URI callbacks. ```APIDOC ## GET /slack/install or /slack/redirect ### Description This endpoint handles GET requests for the OAuth flow. It checks if the request path matches the installation path or the redirect URI path defined in the OAuth flow. If it matches the installation path, it handles the installation process. If it matches the redirect URI path, it handles the callback from Slack. ### Method GET ### Endpoint `/slack/install` or `/slack/redirect` (configurable via `oauth_flow`) ### Parameters None directly on the endpoint, but relies on the `oauth_flow` configuration. ### Request Body None ### Response Handles redirects or returns appropriate responses based on the OAuth flow status. #### Success Response (200 or Redirect) - The response depends on the stage of the OAuth flow. #### Response Example (Varies based on OAuth flow stage and configuration) ``` -------------------------------- ### Initialize InstallationStore and Authorize Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/index.html Configures the installation store and authorize function based on provided settings or environment variables. Handles conflicts and ensures consistent store selection. ```python raise BoltError(error_authorize_conflicts()) self._authorize = CallableAuthorize(logger=self._framework_logger, func=authorize) self._installation_store: Optional[InstallationStore] = installation_store if self._installation_store is not None and self._authorize is None: settings = oauth_flow.settings if oauth_flow is not None else oauth_settings self._authorize = InstallationStoreAuthorize( installation_store=self._installation_store, client_id=settings.client_id if settings is not None else None, client_secret=settings.client_secret if settings is not None else None, logger=self._framework_logger, bot_only=installation_store_bot_only or False, client=self._client, # for proxy use cases etc. user_token_resolution=(settings.user_token_resolution if settings is not None else "authed_user"), ) self._oauth_flow: Optional[OAuthFlow] = None if ( oauth_settings is None and os.environ.get("SLACK_CLIENT_ID") is not None and os.environ.get("SLACK_CLIENT_SECRET") is not None ): # initialize with the default settings oauth_settings = OAuthSettings() if oauth_flow is None and installation_store is None: # show info-level log for avoiding confusions self._framework_logger.info(info_default_oauth_settings_loaded()) if oauth_flow is not None: self._oauth_flow = oauth_flow installation_store = select_consistent_installation_store( client_id=self._oauth_flow.client_id, app_store=self._installation_store, oauth_flow_store=self._oauth_flow.settings.installation_store, logger=self._framework_logger, ) self._installation_store = installation_store if installation_store is not None: self._oauth_flow.settings.installation_store = installation_store if self._oauth_flow._client is None: self._oauth_flow._client = self._client if self._authorize is None: self._authorize = self._oauth_flow.settings.authorize elif oauth_settings is not None: installation_store = select_consistent_installation_store( client_id=oauth_settings.client_id, app_store=self._installation_store, oauth_flow_store=oauth_settings.installation_store, logger=self._framework_logger, ) self._installation_store = installation_store if installation_store is not None: oauth_settings.installation_store = installation_store self._oauth_flow = OAuthFlow(client=self.client, logger=self.logger, settings=oauth_settings) if self._authorize is None: self._authorize = self._oauth_flow.settings.authorize self._authorize.token_rotation_expiration_minutes = oauth_settings.token_rotation_expiration_minutes # type: ignore[attr-defined] # noqa: E501 if (self._installation_store is not None or self._authorize is not None) and self._token is not None: self._token = None self._framework_logger.warning(warning_token_skipped()) # after setting bot_only here, __init__ cannot replace authorize function if installation_store_bot_only is not None and self._oauth_flow is not None: app_bot_only = installation_store_bot_only or False oauth_flow_bot_only = self._oauth_flow.settings.installation_store_bot_only if app_bot_only != oauth_flow_bot_only: self.logger.warning(warning_bot_only_conflicts()) self._oauth_flow.settings.installation_store_bot_only = app_bot_only self._authorize.bot_only = app_bot_only # type: ignore[union-attr] self._tokens_revocation_listeners: Optional[TokenRevocationListeners] = None if self._installation_store is not None: self._tokens_revocation_listeners = TokenRevocationListeners(self._installation_store) # -------------------------------------- # Middleware Initialization # -------------------------------------- self._middleware_list: List[Middleware] = [] self._listeners: List[Listener] = [] if listener_executor is None: ``` -------------------------------- ### Initialize and use AsyncApp Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_app.html Demonstrates how to initialize an AsyncApp instance with credentials and register a message listener. ```python import os from slack_bolt.async_app import AsyncApp # Initializes your app with your bot token and signing secret app = AsyncApp( token=os.environ.get("SLACK_BOT_TOKEN"), signing_secret=os.environ.get("SLACK_SIGNING_SECRET") ) # Listens to incoming messages that contain "hello" @app.message("hello") async def message_hello(message, say): # async function ``` -------------------------------- ### OAuth Flow Handling (GET Requests) Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/django/handler.html Describes how GET requests are handled for initiating and completing the OAuth flow, including installation and callback redirection. ```APIDOC ## OAuth Flow Handling ### Description Handles GET requests specifically for the OAuth flow. This includes initiating the installation process and responding to the redirect URI callback from Slack. ### Method `handle(req: HttpRequest) -> HttpResponse` (within the GET request block) ### Logic for GET Requests 1. Checks if `self.app.oauth_flow` is configured. 2. If `req.path` matches `oauth_flow.install_path`, it calls `oauth_flow.handle_installation()`. 3. If `req.path` matches `oauth_flow.redirect_uri_path`, it calls `oauth_flow.handle_callback()`. 4. Converts the Bolt response to a Django `HttpResponse`. ``` -------------------------------- ### GET / SlackAppResource Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/resource.html Handles Slack OAuth installation and callback requests. ```APIDOC ## GET / (OAuth Flow) ### Description Handles Slack OAuth installation requests and redirect URI callbacks if OAuth flow is configured. ### Method GET ### Endpoint / (Path determined by oauth_flow configuration) ### Response #### Success Response (200) - **bolt_resp** (object) - The response generated by the OAuth flow handler. #### Error Response (404) - **body** (string) - "The page is not found..." ``` -------------------------------- ### GET / (OAuth Flow) Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/async_resource.html Handles Slack OAuth installation and callback requests. ```APIDOC ## GET [path] ### Description Handles the OAuth installation path or the redirect URI path for Slack app authorization. ### Method GET ### Endpoint Defined by oauth_flow.install_path or oauth_flow.redirect_uri_path ### Response #### Success Response (200) - **bolt_resp** (object) - The response generated by the OAuth flow handler. ``` -------------------------------- ### start Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/index.html Starts a web server for local development, allowing incoming requests from Slack to be handled. ```APIDOC ## start ### Description Starts a web server for local development. For production, consider using a production-ready WSGI server such as Gunicorn. ### Method `start( port: int = 3000, path: str = "/slack/events", http_server_logger_enabled: bool = True, )` ### Parameters - **port** (`int`): The port to listen on (Default: 3000). - **path** (`str`): The path to handle requests from Slack (Default: `/slack/events`). - **http_server_logger_enabled** (`bool`): The flag to enable http.server logging if True (Default: True). ### Usage Example ```python # With the default settings, `http://localhost:3000/slack/events` # is available for handling incoming requests from Slack app.start() ``` ``` -------------------------------- ### GET / (OAuth Flow) Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/django/index.html Handles Slack OAuth installation and callback requests. ```APIDOC ## GET /install ### Description Handles the initial Slack OAuth installation request. ### Method GET ### Endpoint /install ### Parameters #### Path Parameters - **req** (django.http.request.HttpRequest) - Required - The Django HTTP request object. ## GET /callback ### Description Handles the Slack OAuth callback request after installation. ### Method GET ### Endpoint /callback ### Parameters #### Path Parameters - **req** (django.http.request.HttpRequest) - Required - The Django HTTP request object. ``` -------------------------------- ### Clone the project repository Source: https://github.com/slackapi/bolt-python/blob/main/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md Download the starter template from GitHub. ```bash git clone https://github.com/slack-samples/bolt-python-jira-functions.git ``` -------------------------------- ### Handle Chalice GET Request for OAuth Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/aws_lambda/chalice_handler.html Handles GET requests for Chalice, specifically for OAuth flows. It distinguishes between installation and callback requests based on query parameters. ```python if method == "GET": if self.app.oauth_flow is not None: oauth_flow: OAuthFlow = self.app.oauth_flow bolt_req: BoltRequest = to_bolt_request(request, body) query = bolt_req.query is_callback = query is not None and ( (_first_value(query, "code") is not None and _first_value(query, "state") is not None) or _first_value(query, "error") is not None ) if is_callback: bolt_resp = oauth_flow.handle_callback(bolt_req) return to_chalice_response(bolt_resp) else: bolt_resp = oauth_flow.handle_installation(bolt_req) return to_chalice_response(bolt_resp) ``` -------------------------------- ### ChaliceSlackRequestHandler.handle (OAuth Callback) Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/aws_lambda/chalice_handler.html Handles GET requests for OAuth flows, including installation and callback handling. This is used when a user installs the app or completes the OAuth authorization process. ```APIDOC ## GET /slack/install ### Description Handles GET requests for initiating or completing the Slack OAuth flow. This endpoint is used for app installation and handling the OAuth callback. ### Method GET ### Endpoint /slack/install ### Query Parameters - **code** (string) - Optional - The authorization code received from Slack during the OAuth callback. - **state** (string) - Optional - The state parameter used to maintain state during the OAuth flow. - **error** (string) - Optional - An error code if the OAuth flow failed. ### Response #### Success Response (200) - **status_code** (integer) - The HTTP status code of the response. - **body** (string) - The response body, typically a JSON string indicating the result of the OAuth flow. #### Response Example ```json { "statusCode": 200, "body": "{\"ok\": true, \"message\": \"App installed successfully!\"}" } ``` ``` -------------------------------- ### Handle GET Requests for OAuth Flow - Bolt Python Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/async_server.html Handles incoming GET requests, routing them to the appropriate OAuth flow endpoints (installation or callback). Requires an OAuth flow to be configured. ```python async def handle_get_requests(self, request: web.Request) -> web.Response: oauth_flow = self._bolt_oauth_flow if oauth_flow: if request.path == oauth_flow.install_path: bolt_req = await to_bolt_request(request) bolt_resp = await oauth_flow.handle_installation(bolt_req) return await to_aiohttp_response(bolt_resp) elif request.path == oauth_flow.redirect_uri_path: bolt_req = await to_bolt_request(request) bolt_resp = await oauth_flow.handle_callback(bolt_req) return await to_aiohttp_response(bolt_resp) else: return web.Response(status=404) else: return web.Response(status=404) ``` -------------------------------- ### AsyncApp Initialization Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/async_app.html Demonstrates how to initialize the AsyncApp with essential credentials and optional configurations. ```APIDOC ## AsyncApp Initialization ### Description Initializes the AsyncApp with your bot token and signing secret. This is the primary class for building Slack applications with Bolt for Python. ### Method ```python AsyncApp( *, logger: Optional[logging.Logger] = None, name: Optional[str] = None, process_before_response: bool = False, raise_error_for_unhandled_request: bool = False, signing_secret: Optional[str] = None, token: Optional[str] = None, client: Optional[slack_sdk.web.async_client.AsyncWebClient] = None, before_authorize: Optional[Union[AsyncMiddleware, Callable[..., Awaitable[Any]]]] = None, authorize: Optional[Callable[..., Awaitable[AuthorizeResult]]] = None, user_facing_authorize_error_message: Optional[str] = None, installation_store: Optional[AsyncInstallationStore] = None, installation_store_bot_only: Optional[bool] = None, request_verification_enabled: bool = True, ignoring_self_events_enabled: bool = True, ignoring_self_assistant_message_events_enabled: bool = True, ssl_check_enabled: bool = True, url_verification_enabled: bool = True, attaching_function_token_enabled: bool = True, oauth_settings: Optional[AsyncOAuthSettings] = None, oauth_flow: Optional[AsyncOAuthFlow] = None, verification_token: Optional[str] = None, assistant_thread_context_store: Optional[AsyncAssistantThreadContextStore] = None, attaching_conversation_kwargs_enabled: bool = True, ) ``` ### Parameters #### Required Parameters - **token** (str) - Your Slack bot token. - **signing_secret** (str) - Your Slack app's signing secret. #### Optional Parameters - **logger** (logging.Logger) - A custom logger instance. - **name** (str) - A name for the app, used in logging. - **process_before_response** (bool) - If True, processes middleware before sending a response (useful for FaaS platforms). - **raise_error_for_unhandled_request** (bool) - If True, unhandled requests will raise an exception. - **client** (AsyncWebClient) - A pre-configured Slack WebClient instance. - **before_authorize** (AsyncMiddleware | Callable) - Middleware to run before the authorization process. - **authorize** (Callable) - A custom authorization function. - **user_facing_authorize_error_message** (str) - Message to display to users on authorization errors. - **installation_store** (AsyncInstallationStore) - A store for managing installation data. - **installation_store_bot_only** (bool) - If True, the installation store only stores bot information. - **request_verification_enabled** (bool) - Enables or disables request verification. - **ignoring_self_events_enabled** (bool) - Enables or disables ignoring events from the bot itself. - **ignoring_self_assistant_message_events_enabled** (bool) - Enables or disables ignoring assistant messages from the bot itself. - **ssl_check_enabled** (bool) - Enables or disables SSL certificate checks. - **url_verification_enabled** (bool) - Enables or disables URL verification. - **attaching_function_token_enabled** (bool) - Enables or disables attaching function tokens. - **oauth_settings** (AsyncOAuthSettings) - Settings for the OAuth flow. - **oauth_flow** (AsyncOAuthFlow) - A custom OAuth flow implementation. - **verification_token** (str) - Verification token (used internally for SSL checks). - **assistant_thread_context_store** (AsyncAssistantThreadContextStore) - Store for AI assistant thread context. - **attaching_conversation_kwargs_enabled** (bool) - Enables or disables attaching conversation keyword arguments. ### Request Example ```python import os from slack_bolt.async_app import AsyncApp app = AsyncApp( token=os.environ.get("SLACK_BOT_TOKEN"), signing_secret=os.environ.get("SLACK_SIGNING_SECRET") ) ``` ### Response This constructor does not return a value, but initializes the `AsyncApp` instance. ``` -------------------------------- ### GET /slack/install and /slack/oauth_redirect Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/tornado/index.html Handles Slack OAuth installation and callback flows within a Tornado application. ```APIDOC ## GET /slack/install and /slack/oauth_redirect ### Description Handles the Slack OAuth flow. The install path initiates the installation, while the redirect URI path handles the callback from Slack. ### Method GET ### Endpoint /slack/install or /slack/oauth_redirect ### Parameters #### Query Parameters - **code** (string) - Optional - The authorization code provided by Slack during the callback. - **state** (string) - Optional - The state parameter for CSRF protection. ``` -------------------------------- ### GET AsyncSlackOAuthHandler Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/tornado/async_handler.html Handles OAuth installation and callback requests for Slack apps within a Tornado application. ```APIDOC ## GET [install_path] or [redirect_uri_path] ### Description Handles the Slack OAuth flow, including the initial installation request and the subsequent callback after user authorization. ### Method GET ### Endpoint Defined by the app's oauth_flow configuration (install_path or redirect_uri_path). ### Response #### Success Response (200) - **bolt_resp** (object) - The response generated by the OAuth flow handler. ``` -------------------------------- ### Accessing InstallationStore Instance Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/app.html Get the slack_sdk.oauth.InstallationStore instance. This store is used by the authorize middleware to manage installation data. ```python @property def installation_store(self) -> Optional[InstallationStore]: """The `slack_sdk.oauth.InstallationStore` that can be used in the `authorize` middleware.""" return self._installation_store ``` -------------------------------- ### Starting the Development Server Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/app/app.html Starts a web server for local development, making your app accessible for handling incoming requests from Slack. ```APIDOC ## start ### Description Starts a web server for local development. ### Method Signature `def start(self, port: int = 3000, path: str = '/slack/events', http_server_logger_enabled: bool = True) -> None` ### Parameters #### `port` (int) - The port to listen on. Defaults to 3000. #### `path` (str) - The path to handle requests from Slack. Defaults to `/slack/events`. #### `http_server_logger_enabled` (bool) - The flag to enable http.server logging if True. Defaults to True. ### Usage Example ```python # With the default settings, `http://localhost:3000/slack/events` # is available for handling incoming requests from Slack app.start() ``` ### Notes This method internally starts a Web server process built with the `http.server` module. For production, consider using a production-ready WSGI server such as Gunicorn. ``` -------------------------------- ### SlackRequestHandler Handle Installation Method Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/wsgi/handler.html The handle_installation method manages the OAuth installation flow for Slack applications. ```APIDOC ## GET /slack/install (Example Endpoint) ### Description Handles the OAuth installation process for Slack applications. ### Method GET ### Endpoint /slack/install ### Parameters #### Path Parameters None #### Query Parameters - **code** (string) - Required - The authorization code received from Slack. - **state** (string) - Optional - The state parameter for CSRF protection. ### Request Example ``` /slack/install?code=AUTHORIZATION_CODE&state=SOME_STATE ``` ### Response #### Success Response (200) - **response** (BoltResponse) - The response indicating the installation status. #### Response Example ```json { "statusCode": 200, "body": "Installation successful!" } ``` ``` -------------------------------- ### Handle GET requests in SlackAppResource Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/index.html Processes OAuth installation and callback paths if configured, otherwise returns a 404 status. ```python def on_get(self, req: Request, resp: Response): if self.app.oauth_flow is not None: oauth_flow: OAuthFlow = self.app.oauth_flow if req.path == oauth_flow.install_path: bolt_resp = oauth_flow.handle_installation(self._to_bolt_request(req)) self._write_response(bolt_resp, resp) return elif req.path == oauth_flow.redirect_uri_path: bolt_resp = oauth_flow.handle_callback(self._to_bolt_request(req)) 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..." ``` -------------------------------- ### Example Usage of AsyncConfigure Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/workflows/step/utilities/async_configure.html An example demonstrating how to use the `configure` utility within a workflow step's `edit` function to send a modal view. This includes defining input blocks and calling the `configure` function. ```python async def edit(ack, step, configure): await ack() blocks = [ { "type": "input", "block_id": "task_name_input", "element": { "type": "plain_text_input", "action_id": "name", "placeholder": {"type": "plain_text", "text": "Add a task name"}, }, "label": {"type": "plain_text", "text": "Task name"}, }, ] await configure(blocks=blocks) ws = AsyncWorkflowStep( callback_id="add_task", edit=edit, save=save, execute=execute, ) app.step(ws) ``` -------------------------------- ### Internal installation helper methods Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/oauth/index.html Utility methods for issuing state, generating authorization URLs, and managing headers. ```python def issue_new_state(self, request: BoltRequest) -> str: return self.settings.state_store.issue() def build_authorize_url(self, state: str, request: BoltRequest) -> str: team_ids: Optional[Sequence[str]] = request.query.get("team") return self.settings.authorize_url_generator.generate( state=state, team=team_ids[0] if team_ids is not None else None, ) def build_install_page_html(self, url: str, request: BoltRequest) -> str: return _build_default_install_page_html(url) def append_set_cookie_headers(self, headers: dict, set_cookie_value: Optional[str]): if set_cookie_value is not None: headers["Set-Cookie"] = [set_cookie_value] return headers ``` -------------------------------- ### SlackRequestHandler Handle Method Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/bottle/index.html The handle method processes GET and POST requests. For GET requests, it manages OAuth installation and callback flows. For POST requests, it dispatches events to the Bolt app. Returns 'Not Found' for other methods or paths. ```python def handle(self, req: Request, resp: Response) -> str: if req.method == "GET": if self.app.oauth_flow is not None: oauth_flow: OAuthFlow = self.app.oauth_flow if req.path == oauth_flow.install_path: bolt_resp = oauth_flow.handle_installation(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.path == oauth_flow.redirect_uri_path: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.method == "POST": bolt_resp = self.app.dispatch(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" resp.status = 404 return "Not Found" ``` -------------------------------- ### GET /slack/install Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/index.html Initiates the Slack OAuth installation flow. This endpoint is configured if an `install_path` is provided in the `oauth_flow` settings of your Bolt App. ```APIDOC ## GET /slack/install ### Description Handles the initiation of the Slack OAuth installation flow. ### Method GET ### Endpoint /slack/install (or custom path defined in `oauth_flow.install_path`) ### Parameters #### Query Parameters - **code** (string) - Optional - The authorization code received from Slack. - **state** (string) - Optional - The state parameter used for CSRF protection. ### Response #### Success Response (200) - **status** (string) - The HTTP status code and phrase. - **body** (string) - The response body, typically an HTML page or a redirect. - **first_headers_without_set_cookie** (object) - Headers to be sent with the response. - **cookies** (array) - Cookies to be set with the response. ### Response Example ```json { "status": "200 OK", "body": "...", "first_headers_without_set_cookie": { "content-type": "text/html" }, "cookies": [] } ``` ``` -------------------------------- ### Start the local server Source: https://github.com/slackapi/bolt-python/blob/main/docs/english/tutorial/custom-steps-for-jira/custom-steps-for-jira.md Run the application locally to begin receiving events. ```bash python app.py ``` -------------------------------- ### Starting the Development Server Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/index.html Starts a web server for local development. For production, consider using a production-ready WSGI server such as Gunicorn. ```APIDOC ## start ### Description Starts a web server for local development. With the default settings, `http://localhost:3000/slack/events` is available for handling incoming requests from Slack. ### Method Signature `start(self, port: int = 3000, path: str = '/slack/events', http_server_logger_enabled: bool = True) -> None` ### Parameters #### `port` The port to listen on (Default: 3000) #### `path` The path to handle request from Slack (Default: `/slack/events`) #### `http_server_logger_enabled` The flag to enable http.server logging if True (Default: True) ### Usage Example ```python # With the default settings, `http://localhost:3000/slack/events` # is available for handling incoming requests from Slack app.start() ``` ``` -------------------------------- ### Handle GET Requests in Falcon AsyncSlackAppResource Source: https://github.com/slackapi/bolt-python/blob/main/docs/reference/adapter/falcon/async_resource.html Handles incoming GET requests for Slack app installation and redirect URIs. It checks for an OAuth flow and delegates handling to the `oauth_flow` object. If no OAuth flow is configured, it returns a 404 Not Found response. ```python async def on_get(self, req: Request, resp: Response): if self.app.oauth_flow is not None: oauth_flow: AsyncOAuthFlow = self.app.oauth_flow if req.path == oauth_flow.install_path: bolt_resp = await oauth_flow.handle_installation(await self._to_bolt_request(req)) await self._write_response(bolt_resp, resp) return elif req.path == oauth_flow.redirect_uri_path: bolt_resp = await oauth_flow.handle_callback(await self._to_bolt_request(req)) 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..." ```