### OAuth Installation Flow Setup Source: https://context7.com/slackapi/python-slack-sdk/llms.txt Provides the foundational imports and setup for implementing Slack OAuth installation flows using Flask and the slack-sdk installation store. ```python import os import html from slack_sdk import WebClient from slack_sdk.oauth import AuthorizeUrlGenerator from slack_sdk.oauth.installation_store import FileInstallationStore, Installation from slack_sdk.oauth.state_store import FileOAuthStateStore from flask import Flask, request, make_response, redirect ``` -------------------------------- ### Manage Custom Installation Values Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Methods to get, set, and serialize custom metadata values associated with an installation. These methods allow for flexible storage of additional application-specific data. ```python def get_custom_value(self, name: str) -> Optional[Any]: return self.custom_values.get(name) def set_custom_value(self, name: str, value: Any): self.custom_values[name] = value def to_dict(self) -> Dict[str, Any]: return {**self.custom_values, **self._to_standard_value_dict()} def to_dict_for_copying(self) -> Dict[str, Any]: return {"custom_values": self.custom_values, **self._to_standard_value_dict()} ``` -------------------------------- ### Set Up Python Virtual Environment and Install slack_sdk (Bash) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/english/installation.md This bash script outlines the steps to create and activate a Python virtual environment using `venv`, install the `slack_sdk` package from PyPI, and set the Slack bot token as an environment variable. This is a common setup procedure for Python projects interacting with the Slack API. ```bash # Create a dedicated virtual environment for your Python project python -m venv .venv # Activate the virtual environment # On Windows OS, use: .\.venv\Scripts\activate source .venv/bin/activate # Install the slack_sdk package from PyPI, ensuring version 3.0 or higher pip install "slack_sdk>=3.0" # Set your Slack Bot Token as an environment variable # On Windows OS, use: set SLACK_BOT_TOKEN=xoxb-*** export SLACK_BOT_TOKEN=xoxb-*** # After setting up, you can run your Python scripts within this activated environment. # To deactivate the environment, simply type: deactivate ``` -------------------------------- ### Installation Object Methods Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Methods available on an Installation object for accessing installation-specific data. ```APIDOC ## Installation Object Methods ### Description Provides access to various attributes and methods related to a Slack app installation. ### Methods - **enterprise_url()**: Get the enterprise URL. - **get_custom_value(key)**: Retrieve a custom value stored for the installation. - **incoming_webhook_channel()**: Get the incoming webhook channel. - **incoming_webhook_channel_id()**: Get the incoming webhook channel ID. - **incoming_webhook_configuration_url()**: Get the incoming webhook configuration URL. - **incoming_webhook_url()**: Get the incoming webhook URL. - **installed_at()**: Get the timestamp when the app was installed. - **is_enterprise_install()**: Check if the installation is for an enterprise grid. - **set_custom_value(key, value)**: Store a custom value for the installation. - **team_id()**: Get the team ID for the installation. - **team_name()**: Get the team name for the installation. - **to_bot()**: Get the bot token and scopes. - **to_dict()**: Convert the installation object to a dictionary. - **to_dict_for_copying()**: Convert the installation object to a dictionary suitable for copying. - **token_type()**: Get the token type (e.g., 'bot', 'user'). - **user_id()**: Get the user ID associated with the installation. - **user_refresh_token()**: Get the user's refresh token. - **user_scopes()**: Get the user's granted scopes. - **user_token()**: Get the user's access token. - **user_token_expires_at()**: Get the expiration timestamp for the user token. ``` -------------------------------- ### Convert Installation to Standard Dictionary (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Converts the Installation object's attributes into a standard Python dictionary format. This is useful for serialization or when an API expects a dictionary representation of the installation data. ```python def _to_standard_value_dict(self) -> Dict[str, Any]: return { "app_id": self.app_id, "enterprise_id": self.enterprise_id, "enterprise_name": self.enterprise_name, "enterprise_url": self.enterprise_url, "team_id": self.team_id, "team_name": self.team_name, "bot_token": self.bot_token, "bot_id": self.bot_id, "bot_user_id": self.bot_user_id, "bot_scopes": ",".join(self.bot_scopes) if self.bot_scopes else None, "bot_refresh_token": self.bot_refresh_token, "bot_token_expires_at": ( datetime.fromtimestamp(self.bot_token_expires_at, tz=timezone.utc) if self.bot_token_expires_at else None ) ``` -------------------------------- ### Manage Custom Values in Installation (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Provides methods to set and get custom values associated with a Slack installation. These methods operate on the `custom_values` dictionary within the Installation object, allowing for flexible storage of additional data. ```python def set_custom_value(self, name: str, value: Any): self.custom_values[name] = value def get_custom_value(self, name: str) -> Optional[Any]: return self.custom_values.get(name) ``` -------------------------------- ### Python Slack SDK: Installation Data Class Methods Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html This snippet demonstrates methods within a Python class designed to manage Slack installation data. It includes functions to set and get custom values, and to convert the installation data into standard dictionary formats for internal use or copying. Dependencies include Python's datetime and timezone modules. ```python from datetime import datetime, timezone from typing import Any, Dict, Optional, Sequence def _timestamp_to_type(timestamp: float, type_hint: type) -> Any: # Placeholder for actual timestamp conversion logic return type_hint(timestamp) class SlackInstallation: def __init__(self, app_id: Optional[str] = None, enterprise_id: Optional[str] = None, enterprise_name: Optional[str] = None, team_id: Optional[str] = None, team_name: Optional[str] = None, bot_token: Optional[str] = None, bot_id: Optional[str] = None, bot_user_id: Optional[str] = None, bot_scopes: Optional[Sequence[str]] = None, bot_refresh_token: Optional[str] = None, bot_token_expires_at: Optional[float] = None, is_enterprise_install: bool = False, installed_at: float = 0.0, custom_values: Optional[Dict[str, Any]] = None): self.app_id = app_id self.enterprise_id = enterprise_id self.enterprise_name = enterprise_name self.team_id = team_id self.team_name = team_name self.bot_token = bot_token self.bot_id = bot_id self.bot_user_id = bot_user_id self.bot_scopes = bot_scopes if bot_scopes is not None else [] self.bot_refresh_token = bot_refresh_token self.bot_token_expires_at = bot_token_expires_at self.is_enterprise_install = is_enterprise_install self.installed_at = _timestamp_to_type(installed_at, float) self.custom_values = custom_values if custom_values is not None else {} def set_custom_value(self, name: str, value: Any): self.custom_values[name] = value def get_custom_value(self, name: str) -> Optional[Any]: return self.custom_values.get(name) def _to_standard_value_dict(self) -> Dict[str, Any]: return { "app_id": self.app_id, "enterprise_id": self.enterprise_id, "enterprise_name": self.enterprise_name, "team_id": self.team_id, "team_name": self.team_name, "bot_token": self.bot_token, "bot_id": self.bot_id, "bot_user_id": self.bot_user_id, "bot_scopes": ",".join(self.bot_scopes) if self.bot_scopes else None, "bot_refresh_token": self.bot_refresh_token, "bot_token_expires_at": ( datetime.fromtimestamp(self.bot_token_expires_at, tz=timezone.utc) if self.bot_token_expires_at is not None else None ), "is_enterprise_install": self.is_enterprise_install, "installed_at": datetime.fromtimestamp(self.installed_at, tz=timezone.utc), } def to_dict_for_copying(self) -> Dict[str, Any]: return {"custom_values": self.custom_values, **self._to_standard_value_dict()} def to_dict(self) -> Dict[str, Any]: # prioritize standard_values over custom_values # when the same keys exist in both return {**self.custom_values, **self._to_standard_value_dict()} ``` -------------------------------- ### Convert Installation to Bot Object (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Converts the current Installation object into a Bot object. This method extracts relevant attributes from the Installation instance to populate the Bot instance, useful for interacting with Slack APIs as a bot. ```python def to_bot(self) -> Bot: return Bot( app_id=self.app_id, enterprise_id=self.enterprise_id, enterprise_name=self.enterprise_name, team_id=self.team_id, team_name=self.team_name, bot_token=self.bot_token, # type: ignore[arg-type] bot_id=self.bot_id, # type: ignore[arg-type] bot_user_id=self.bot_user_id, # type: ignore[arg-type] bot_scopes=self.bot_scopes, # type: ignore[arg-type] bot_refresh_token=self.bot_refresh_token, bot_token_expires_at=self.bot_token_expires_at, is_enterprise_install=self.is_enterprise_install, installed_at=self.installed_at, custom_values=self.custom_values, ) ``` -------------------------------- ### Query Installation Entity Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html Fetches the latest installation record, optionally filtering by user ID. It includes logic to merge bot token information if the installation record is missing it. ```python def find_installation(self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = None c = self.installations.c where_clause = and_(c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id) if user_id is not None: where_clause = and_(c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, c.user_id == user_id) query = self.installations.select().where(where_clause).order_by(desc(c.installed_at)).limit(1) # ... (logic to execute and merge bot data) ``` -------------------------------- ### Install Slack SDK Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/english/installation.md Commands to install the Slack SDK package using pip or by cloning the repository from source. ```bash pip install slack-sdk ``` ```bash git clone https://github.com/slackapi/python-slack-sdk.git cd python-slack-sdk python3 -m venv .venv source .venv/bin/activate pip install -U pip pip install -e . ``` -------------------------------- ### Finding Installation Data Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html This section covers methods for finding bot and general installation data based on provided IDs. ```APIDOC ## GET /slack/installation/bot ### Description Finds a bot scope installation per workspace or organization. ### Method GET ### Endpoint /slack/installation/bot ### Parameters #### Query Parameters - **enterprise_id** (string) - Required - The ID of the enterprise. - **team_id** (string) - Required - The ID of the team. - **is_enterprise_install** (boolean) - Optional - Defaults to `false`. Indicates if it's an enterprise installation. ### Response #### Success Response (200) - **bot** (object) - The bot installation details. - **id** (string) - The bot ID. - **scopes** (array) - List of scopes. - **token** (string) - The bot token. ## GET /slack/installation ### Description Finds a relevant installation for the given IDs. If the user_id is absent, this method may return the latest installation in the workspace or org. ### Method GET ### Endpoint /slack/installation ### Parameters #### Query Parameters - **enterprise_id** (string) - Optional - The ID of the enterprise. - **team_id** (string) - Optional - The ID of the team. - **user_id** (string) - Optional - The ID of the user. - **is_enterprise_install** (boolean) - Optional - Defaults to `false`. Indicates if it's an enterprise installation. ### Response #### Success Response (200) - **installation** (object) - The installation details. - **id** (string) - The installation ID. - **scopes** (array) - List of scopes. - **token** (string) - The access token. - **user_id** (string) - The user ID. - **team_id** (string) - The team ID. - **enterprise_id** (string) - The enterprise ID. ``` -------------------------------- ### Define Installation Data Model in Python Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/models/installation.html The Installation class serves as a container for Slack app installation data. It supports optional fields for bot and user tokens, token rotation metadata, and incoming webhook configurations. ```python class Installation: def __init__( self, *, app_id: Optional[str] = None, enterprise_id: Optional[str] = None, team_id: Optional[str] = None, bot_token: Optional[str] = None, user_id: str, user_token: Optional[str] = None, installed_at: Optional[Union[float, datetime, str]] = None, custom_values: Optional[Dict[str, Any]] = None, **kwargs ): self.app_id = app_id self.enterprise_id = enterprise_id self.team_id = team_id self.bot_token = bot_token self.user_id = user_id self.user_token = user_token self.installed_at = installed_at self.custom_values = custom_values or {} ``` -------------------------------- ### Manage Database Table Creation Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html Method to initialize database tables using the configured engine and metadata. This is typically called during the setup phase of the installation store. ```python def create_tables(self): self.metadata.create_all(self.engine) ``` -------------------------------- ### SQLAlchemy Installation Store Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html This section details the SQLAlchemy installation store, which is used to persist installation data for Slack applications. It allows for efficient storage and retrieval of installation information using a relational database. ```APIDOC ## SQLAlchemy Installation Store ### Description Provides a SQLAlchemy-based implementation for storing and retrieving Slack app installation data. This is useful for applications that need to persist installation details in a relational database. ### Method N/A (This is a class/module documentation, not an API endpoint) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Saving Installation Data Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html This section covers methods for saving bot and general installation data. ```APIDOC ## POST /slack/installation ### Description Saves an installation data. ### Method POST ### Endpoint /slack/installation ### Parameters #### Request Body - **installation** (object) - Required - The installation data to save. - **id** (string) - The installation ID. - **scopes** (array) - List of scopes. - **token** (string) - The access token. - **user_id** (string) - The user ID. - **team_id** (string) - The team ID. - **enterprise_id** (string) - The enterprise ID. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ## POST /slack/installation/bot ### Description Saves a bot installation data. ### Method POST ### Endpoint /slack/installation/bot ### Parameters #### Request Body - **bot** (object) - Required - The bot installation data to save. - **id** (string) - The bot ID. - **scopes** (array) - List of scopes. - **token** (string) - The bot token. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` -------------------------------- ### Find Slack Installation Data with SQLAlchemy Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html This method retrieves Slack installation data, optionally filtering by user ID. It first attempts to find a general installation and then, if necessary (e.g., user ID is provided or bot token is missing), it also fetches the latest bot installation to ensure all relevant data is present. It returns an Installation object or None. ```python async def async_find_installation( self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False, ) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = None c = self.installations.c where_clause = and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, ) if user_id is not None: where_clause = and_( c.client_id == self.client_id, c.enterprise_id == enterprise_id, c.team_id == team_id, c.user_id == user_id, ) query = self.installations.select().where(where_clause).order_by(desc(c.installed_at)).limit(1) installation: Optional[Installation] = None async with self.engine.connect() as conn: result: object = await conn.execute(query) for row in result.mappings(): # type: ignore[attr-defined] installation = SQLAlchemyInstallationStore.build_installation_entity(row) has_user_installation = user_id is not None and installation is not None no_bot_token_installation = installation is not None and installation.bot_token is None should_find_bot_installation = has_user_installation or no_bot_token_installation if should_find_bot_installation: # Retrieve the latest bot token, just in case # See also: https://github.com/slackapi/bolt-python/issues/664 latest_bot_installation = await self.async_find_bot( enterprise_id=enterprise_id, team_id=team_id, is_enterprise_install=is_enterprise_install, ) if ( latest_bot_installation is not None and installation is not None and installation.bot_token != latest_bot_installation.bot_token ): installation.bot_id = latest_bot_installation.bot_id installation.bot_user_id = latest_bot_installation.bot_user_id installation.bot_token = latest_bot_installation.bot_token installation.bot_scopes = latest_bot_installation.bot_scopes installation.bot_refresh_token = latest_bot_installation.bot_refresh_token installation.bot_token_expires_at = latest_bot_installation.bot_token_expires_at return installation ``` -------------------------------- ### Find Slack Installation Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Retrieves installation data based on enterprise ID, team ID, user ID, and installation type. This is crucial for managing existing app installations. ```python find_installation(enterprise_id, team_id, user_id, is_enterprise_install) ``` -------------------------------- ### Find Installation Data in Python Slack SDK Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Methods to retrieve bot or installation objects. These methods support filtering by enterprise, team, and user IDs, and optionally specify if the installation is enterprise-wide. ```python def find_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str], is_enterprise_install: Optional[bool] = False) -> Optional[Bot]: raise NotImplementedError() def find_installation(self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False) -> Optional[Installation]: raise NotImplementedError() ``` -------------------------------- ### Find Installation (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/async_installation_store.html Asynchronously finds an installation matching the provided IDs (enterprise, team, user). If `user_id` is omitted, it may return the latest installation. Returns an `Installation` object or `None`. Raises `NotImplementedError`. ```python async def async_find_installation( self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False, ) -> Optional[Installation]: """Finds a relevant installation for the given IDs. If the user_id is absent, this method may return the latest installation in the workspace / org. """ raise NotImplementedError() ``` -------------------------------- ### Retrieve Bot and Installation Data in Python Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html These methods locate and deserialize JSON-stored bot or installation data from the file system. They handle missing files gracefully and support merging bot token information into user-specific installations. ```python def find_bot(self, *, enterprise_id: Optional[str], team_id: Optional[str], is_enterprise_install: Optional[bool] = False) -> Optional[Bot]: none = "none" e_id = enterprise_id or none t_id = team_id or none if is_enterprise_install: t_id = none bot_filepath = f"{self.base_dir}/{e_id}-{t_id}/bot-latest" try: with open(bot_filepath) as f: data = json.loads(f.read()) return Bot(**data) except FileNotFoundError as e: self.logger.debug(f"Installation data missing: {e}") return None def find_installation(self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False) -> Optional[Installation]: # Logic to retrieve and optionally merge bot data into an installation object ... ``` -------------------------------- ### Define Installation Class Structure Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/models/index.html The Installation class definition, which holds comprehensive state for a Slack app installation, including bot tokens, user tokens, and enterprise/team identifiers. ```python class Installation: def __init__( self, *, app_id: Optional[str] = None, enterprise_id: Optional[str] = None, team_id: Optional[str] = None, bot_token: Optional[str] = None, user_id: str, custom_values: Dict[str, Any] = None ): self.app_id = app_id self.enterprise_id = enterprise_id self.team_id = team_id self.bot_token = bot_token self.user_id = user_id self.custom_values = custom_values or {} ``` -------------------------------- ### Install Python Slack SDK Source: https://context7.com/slackapi/python-slack-sdk/llms.txt Installs the Python Slack SDK using pip. Includes an optional installation for enhanced async support and DNS optimization. ```bash pip install slack_sdk # Optional: Install with async support and DNS optimization pip install slack_sdk[optional] ``` -------------------------------- ### Transform Installation Data Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Utility methods to convert an Installation object into a Bot model or a dictionary representation. These are useful for serialization and API compatibility. ```python def to_bot(self) -> Bot: return Bot( app_id=self.app_id, enterprise_id=self.enterprise_id, enterprise_name=self.enterprise_name, team_id=self.team_id, team_name=self.team_name, bot_token=self.bot_token, bot_id=self.bot_id, bot_user_id=self.bot_user_id, bot_scopes=self.bot_scopes, bot_refresh_token=self.bot_refresh_token, bot_token_expires_at=self.bot_token_expires_at, is_enterprise_install=self.is_enterprise_install, installed_at=self.installed_at, custom_values=self.custom_values, ) def to_dict(self) -> Dict[str, Any]: return {**self.custom_values, **self._to_standard_value_dict()} ``` -------------------------------- ### Save Installation Data in Python Slack SDK Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Methods for persisting installation and bot data to the underlying storage implementation. ```python def save(self, installation: Installation): raise NotImplementedError() def save_bot(self, bot: Bot): raise NotImplementedError() ``` -------------------------------- ### Save Slack Bot Installation Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Saves installation data specifically for bot scope. This is a simpler approach for apps that only require bot permissions. ```python save(installation) ``` -------------------------------- ### Initialize and Use FileInstallationStore Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/file/index.html Demonstrates how to instantiate the FileInstallationStore and utilize its methods to save and retrieve installation data. The class handles directory creation and JSON serialization of installation objects automatically. ```python from slack_sdk.oauth.installation_store.file import FileInstallationStore import logging # Initialize the store store = FileInstallationStore( base_dir="./data", historical_data_enabled=True, logger=logging.getLogger(__name__) ) # Example of saving an installation # store.save(installation_object) # Example of finding a bot bot = store.find_bot( enterprise_id="E123", team_id="T123" ) ``` -------------------------------- ### Initialize and Use AsyncSQLAlchemyInstallationStore Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html The AsyncSQLAlchemyInstallationStore class manages database interactions for Slack installations asynchronously. It requires a SQLAlchemy AsyncEngine and provides methods to create tables and persist installation or bot data. ```python class AsyncSQLAlchemyInstallationStore(AsyncInstallationStore): def __init__(self, client_id, engine, bots_table_name="slack_bots", installations_table_name="slack_installations", logger=None): self.metadata = sqlalchemy.MetaData() self.bots = self.build_bots_table(metadata=self.metadata, table_name=bots_table_name) self.installations = self.build_installations_table(metadata=self.metadata, table_name=installations_table_name) self.client_id = client_id self.engine = engine async def create_tables(self): async with self.engine.begin() as conn: await conn.run_sync(self.metadata.create_all) async def async_save(self, installation: Installation): async with self.engine.begin() as conn: i = installation.to_dict() i["client_id"] = self.client_id # Logic for inserting or updating installation records follows... ``` -------------------------------- ### SQLAlchemyInstallationStore Methods Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/sqlalchemy/index.html Methods for initializing and managing the database schema for Slack installations. ```APIDOC ## POST /create_tables ### Description Initializes the database schema by creating the necessary tables for storing bot and installation data. ### Method POST ### Endpoint /create_tables ### Parameters None ### Request Example {} ### Response #### Success Response (200) - **status** (string) - Confirmation of table creation. #### Response Example { "status": "success" } ## POST /build_installation_entity ### Description Constructs an installation entity object based on the provided Slack installation data. ### Method POST ### Endpoint /build_installation_entity ### Parameters #### Request Body - **installation_data** (object) - Required - The raw data received from the Slack OAuth flow. ### Request Example { "installation_data": { "team_id": "T123", "bot_token": "xoxb-123" } } ### Response #### Success Response (200) - **entity** (object) - The formatted SQLAlchemy entity object. #### Response Example { "entity": { "id": "...", "team_id": "T123" } } ``` -------------------------------- ### GET /admin.apps.restricted.list Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/web/legacy_client.html Lists all apps that have been restricted from installation on a workspace or enterprise. ```APIDOC ## GET /admin.apps.restricted.list ### Description Lists all apps that have been restricted from installation on a workspace or enterprise. ### Method GET ### Endpoint /admin.apps.restricted.list ### Parameters #### Path Parameters None #### Query Parameters - **cursor** (string) - Optional - Set of results to return. Only used when paginating through large result sets. - **limit** (integer) - Optional - The maximum number of items to return. Defaults to 100. - **enterprise_id** (string) - Optional - The ID of the enterprise. - **team_id** (string) - Optional - The ID of the team (workspace). ### Request Example ```json { "limit": 50, "team_id": "T1234567890" } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **restricted_apps** (array) - A list of restricted applications. - **response_metadata** (object) - Contains pagination information. #### Response Example ```json { "ok": true, "restricted_apps": [ { "app_id": "A1234567890", "display_name": "Restricted App" } ], "response_metadata": { "next_cursor": "dGVhbV9pZ..." } } ``` ``` -------------------------------- ### AsyncCacheableInstallationStore Initialization and Caching Logic (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/async_cacheable_installation_store.html This Python code defines the AsyncCacheableInstallationStore class, which acts as a cache layer for Slack installation data. It initializes with an underlying AsyncInstallationStore and maintains dictionaries for cached bot and installation data. The `async_save`, `async_save_bot`, `async_find_bot`, and `async_find_installation` methods demonstrate how the cache is populated and invalidated to ensure data consistency. ```python class AsyncCacheableInstallationStore(AsyncInstallationStore): underlying: AsyncInstallationStore cached_bots: Dict[str, Bot] cached_installations: Dict[str, Installation] def __init__(self, installation_store: AsyncInstallationStore): """A simple memory cache wrapper for any installation stores. Args: installation_store: The installation store to wrap """ self.underlying = installation_store self.cached_bots = {} self.cached_installations = {} @property def logger(self) -> Logger: return self.underlying.logger async def async_save(self, installation: Installation): # Invalidate cache data for update operations key = f"{installation.enterprise_id or ''}-{installation.team_id or ''}" if key in self.cached_bots: self.cached_bots.pop(key) key = f"{installation.enterprise_id or ''}-{installation.team_id or ''}-{installation.user_id or ''}" if key in self.cached_installations: self.cached_installations.pop(key) return await self.underlying.async_save(installation) async def async_save_bot(self, bot: Bot): # Invalidate cache data for update operations key = f"{bot.enterprise_id or ''}-{bot.team_id or ''}" if key in self.cached_bots: self.cached_bots.pop(key) return await self.underlying.async_save_bot(bot) async def async_find_bot( self, *, enterprise_id: Optional[str], team_id: Optional[str], is_enterprise_install: Optional[bool] = False, ) -> Optional[Bot]: if is_enterprise_install or team_id is None: team_id = "" key = f"{enterprise_id or ''}-{team_id or ''}" if key in self.cached_bots: return self.cached_bots[key] bot = await self.underlying.async_find_bot( enterprise_id=enterprise_id, team_id=team_id, is_enterprise_install=is_enterprise_install, ) if bot: self.cached_bots[key] = bot return bot async def async_find_installation( self, *, enterprise_id: Optional[str], team_id: Optional[str], user_id: Optional[str] = None, is_enterprise_install: Optional[bool] = False, ) -> Optional[Installation]: if is_enterprise_install or team_id is None: team_id = "" key = f"{enterprise_id or ''}-{team_id or ''}-{user_id or ''}" if key in self.cached_installations: return self.cached_installations[key] installation = await self.underlying.async_find_installation( enterprise_id=enterprise_id, team_id=team_id, user_id=user_id, is_enterprise_install=is_enterprise_install, ) if installation: self.cached_installations[key] = installation return installation ``` -------------------------------- ### GET /admin.apps.approved.list Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/web/legacy_client.html Lists all apps that have been approved for installation on a workspace or enterprise. ```APIDOC ## GET /admin.apps.approved.list ### Description Lists all apps that have been approved for installation on a workspace or enterprise. ### Method GET ### Endpoint /admin.apps.approved.list ### Parameters #### Path Parameters None #### Query Parameters - **cursor** (string) - Optional - Set of results to return. Only used when paginating through large result sets. - **limit** (integer) - Optional - The maximum number of items to return. Defaults to 100. - **enterprise_id** (string) - Optional - The ID of the enterprise. - **team_id** (string) - Optional - The ID of the team (workspace). ### Request Example ```json { "limit": 50, "team_id": "T1234567890" } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the request was successful. - **approved_apps** (array) - A list of approved applications. - **response_metadata** (object) - Contains pagination information. #### Response Example ```json { "ok": true, "approved_apps": [ { "app_id": "A1234567890", "display_name": "Example App" } ], "response_metadata": { "next_cursor": "dGVhbV9pZ..." } } ``` ``` -------------------------------- ### GET rtm.start Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/index.html Starts a Real Time Messaging session with various configuration options. ```APIDOC ## GET rtm.start ### Description Starts a Real Time Messaging session. ### Method GET ### Endpoint rtm.start ### Parameters #### Query Parameters - **batch_presence_aware** (bool) - Optional - Batch presence updates. - **include_locale** (bool) - Optional - Set this to true to receive locale information. - **mpim_aware** (bool) - Optional - Set this to true to receive multiparty IMs. - **no_latest** (bool) - Optional - Exclude latest messages. - **no_unreads** (bool) - Optional - Exclude unread counts. - **presence_sub** (bool) - Optional - Subscribe to presence events. - **simple_latest** (bool) - Optional - Return only the timestamp of the latest message. ### Request Example { "batch_presence_aware": true, "presence_sub": true } ### Response #### Success Response (200) - **ok** (boolean) - Status of the request. - **url** (string) - The WSS URL for the RTM connection. ``` -------------------------------- ### InstallationStore Methods Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/file/index.html Methods for synchronous management of Slack installation and bot data. ```APIDOC ## POST /installation_store/save ### Description Persists installation data to the store. ### Method POST ### Endpoint /installation_store/save ### Request Body - **installation** (object) - Required - The installation data object to save. ### Response #### Success Response (200) - **status** (string) - Confirmation of successful save. --- ## GET /installation_store/find_installation ### Description Retrieves installation data for a specific enterprise, team, or user. ### Method GET ### Endpoint /installation_store/find_installation ### Query Parameters - **enterprise_id** (string) - Optional - The enterprise ID. - **team_id** (string) - Optional - The team ID. - **user_id** (string) - Optional - The user ID. ### Response #### Success Response (200) - **installation** (object) - The retrieved installation object. ``` -------------------------------- ### GET /admin.apps.restricted.list Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/web/index.html Lists all apps that have been restricted from installation within an organization or workspace. ```APIDOC ## GET /admin.apps.restricted.list ### Description Lists restricted apps for an org or workspace. ### Method GET ### Endpoint /admin.apps.restricted.list ### Parameters #### Path Parameters None #### Query Parameters * **cursor** (str) - Optional - For pagination. Set to the `next_cursor` value returned by the previous request. * **limit** (int) - Optional - The maximum number of items to return. Defaults to 100. * **enterprise_id** (str) - Optional - The ID of the enterprise. * **team_id** (str) - Optional - The ID of the team. ### Request Example ```json { "limit": 50, "enterprise_id": "E1234567890" } ``` ### Response #### Success Response (200) * **ok** (bool) - True if the request was successful. * **restricted_apps** (list) - A list of restricted apps. * **next_cursor** (str) - The cursor for the next page of results. * **error** (str) - Description of the error, if any. #### Response Example ```json { "ok": true, "restricted_apps": [ { "app_id": "A1234567890", "display_name": "Example App" } ], "next_cursor": "" } ``` ``` -------------------------------- ### Initialize and Configure Slack Installation Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/models/index.html The constructor initializes installation properties, handles token expiration logic, and parses comma-separated scope strings. It ensures that timestamps are normalized and custom metadata is stored correctly. ```python def __init__(self, app_id, enterprise_id, enterprise_name, enterprise_url, team_id, team_name, bot_token, bot_id, bot_user_id, bot_scopes, bot_refresh_token, bot_token_expires_at, bot_token_expires_in, user_id, user_token, user_scopes, user_refresh_token, user_token_expires_at, user_token_expires_in, incoming_webhook_url, incoming_webhook_channel, incoming_webhook_channel_id, incoming_webhook_configuration_url=None, is_enterprise_install=False, token_type=None, installed_at=None, custom_values=None): self.app_id = app_id # ... (initialization logic for tokens and scopes) if isinstance(bot_scopes, str): self.bot_scopes = bot_scopes.split(",") if len(bot_scopes) > 0 else [] else: self.bot_scopes = bot_scopes if bot_token_expires_at is not None: self.bot_token_expires_at = _timestamp_to_type(bot_token_expires_at, int) elif bot_token_expires_in is not None: self.bot_token_expires_at = int(time()) + bot_token_expires_in ``` -------------------------------- ### GET /logs Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/audit_logs/async_client.html Retrieves a list of audit events that have occurred on the installed workspace or grid organization. ```APIDOC ## GET /logs ### Description Retrieves a list of audit events from your organization. This is the primary endpoint for monitoring actions taken by users or on entities within the workspace. ### Method GET ### Endpoint /logs ### Parameters #### Query Parameters - **latest** (int) - Optional - Unix timestamp of the most recent audit event to include (inclusive). - **oldest** (int) - Optional - Unix timestamp of the least recent audit event to include (inclusive). - **limit** (int) - Optional - Number of results to return, maximum 9999. - **action** (string) - Optional - Name of the action to filter by. - **actor** (string) - Optional - User ID who initiated the action. - **entity** (string) - Optional - ID of the target entity (e.g., channel, workspace, file). - **cursor** (string) - Optional - The next page cursor for pagination. ### Request Example GET /logs?limit=10&action=user_login ### Response #### Success Response (200) - **entries** (array) - List of audit log events. - **response_metadata** (object) - Pagination metadata including the next cursor. #### Response Example { "entries": [ { "id": "12345", "action": "user_login", "actor": "U12345", "entity": "W12345", "date_create": 1610000000 } ], "response_metadata": { "next_cursor": "dGVzdF9jdXJzb3I=" } } ``` -------------------------------- ### Initialize Slack Installation Configuration (Python) Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Initializes the Slack installation configuration with various details like app ID, team information, bot tokens, and installation timestamps. It handles different input types for scopes and expiration times, and allows for custom values. ```python from datetime import datetime, timezone from time import time from typing import Any, Dict, Optional, Union # Assuming _timestamp_to_type and Bot are defined elsewhere # from .utils import _timestamp_to_type # from .models import Bot class Installation: def __init__( self, app_id: Optional[str] = None, enterprise_id: Optional[str] = None, enterprise_name: Optional[str] = None, enterprise_url: Optional[str] = None, team_id: Optional[str] = None, team_name: Optional[str] = None, bot_token: Optional[str] = None, bot_id: Optional[str] = None, bot_user_id: Optional[str] = None, bot_scopes: Optional[Union[str, list]] = None, bot_refresh_token: Optional[str] = None, bot_token_expires_at: Optional[Union[float, int]] = None, bot_token_expires_in: Optional[int] = None, user_id: Optional[str] = None, user_token: Optional[str] = None, user_scopes: Optional[Union[str, list]] = None, user_refresh_token: Optional[str] = None, user_token_expires_at: Optional[Union[float, int]] = None, user_token_expires_in: Optional[int] = None, incoming_webhook_url: Optional[str] = None, incoming_webhook_channel: Optional[str] = None, incoming_webhook_channel_id: Optional[str] = None, incoming_webhook_configuration_url: Optional[str] = None, is_enterprise_install: Optional[bool] = False, token_type: Optional[str] = None, installed_at: Optional[Union[float, datetime, str]] = None, custom_values: Optional[Dict[str, Any]] = None, ): self.app_id = app_id self.enterprise_id = enterprise_id self.enterprise_name = enterprise_name self.enterprise_url = enterprise_url self.team_id = team_id self.team_name = team_name self.bot_token = bot_token self.bot_id = bot_id self.bot_user_id = bot_user_id if isinstance(bot_scopes, str): self.bot_scopes = bot_scopes.split(",") if len(bot_scopes) > 0 else [] else: self.bot_scopes = bot_scopes self.bot_refresh_token = bot_refresh_token if bot_token_expires_at is not None: # Assuming _timestamp_to_type converts to int self.bot_token_expires_at = _timestamp_to_type(bot_token_expires_at, int) elif bot_token_expires_in is not None: self.bot_token_expires_at = int(time()) + bot_token_expires_in else: self.bot_token_expires_at = None self.user_id = user_id self.user_token = user_token if isinstance(user_scopes, str): self.user_scopes = user_scopes.split(",") if len(user_scopes) > 0 else [] else: self.user_scopes = user_scopes self.user_refresh_token = user_refresh_token if user_token_expires_at is not None: # Assuming _timestamp_to_type converts to int self.user_token_expires_at = _timestamp_to_type(user_token_expires_at, int) elif user_token_expires_in is not None: self.user_token_expires_at = int(time()) + user_token_expires_in else: self.user_token_expires_at = None self.incoming_webhook_url = incoming_webhook_url self.incoming_webhook_channel = incoming_webhook_channel self.incoming_webhook_channel_id = incoming_webhook_channel_id self.incoming_webhook_configuration_url = incoming_webhook_configuration_url self.is_enterprise_install = is_enterprise_install or False self.token_type = token_type if installed_at is None: self.installed_at = datetime.now().timestamp() else: # Assuming _timestamp_to_type converts to float self.installed_at = _timestamp_to_type(installed_at, float) self.custom_values = custom_values if custom_values is not None else {} ``` -------------------------------- ### GET /rtm.connect Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/web/index.html Starts a Real Time Messaging session with the Slack platform. ```APIDOC ## GET /rtm.connect ### Description Starts a Real Time Messaging session. ### Method GET ### Endpoint /rtm.connect ### Parameters #### Query Parameters - **batch_presence_aware** (boolean) - Optional - Whether to receive batch presence events. - **presence_sub** (boolean) - Optional - Whether to subscribe to presence events. ### Request Example { "presence_sub": true } ### Response #### Success Response (200) - **ok** (boolean) - Indicates success. - **url** (string) - The WebSocket URL for the RTM session. #### Response Example { "ok": true, "url": "wss://ws1.slack.com/..." } ``` -------------------------------- ### InstallationStore Object Methods Source: https://github.com/slackapi/python-slack-sdk/blob/main/docs/reference/oauth/installation_store/index.html Methods for managing the storage and retrieval of Slack app installations. ```APIDOC ## InstallationStore Object Methods ### Description Provides methods to interact with the installation store, allowing you to save, find, and delete installation data. ### Methods - **delete_all()**: Delete all installations from the store. - **delete_bot(enterprise_id, team_id)**: Delete bot installation data for a given enterprise and team. - **delete_installation(enterprise_id, team_id, user_id)**: Delete a specific user installation. - **find_bot(enterprise_id, team_id)**: Find bot installation data for a given enterprise and team. - **find_installation(enterprise_id, team_id, user_id)**: Find a specific user installation. - **logger()**: Get the logger instance used by the store. - **save(installation)**: Save an installation object to the store. - **save_bot(installation)**: Save bot installation data to the store. ```